home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Modules / socketmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-03  |  70.4 KB  |  2,840 lines

  1. /* Socket module */
  2.  
  3. /* SSL support based on patches by Brian E Gallew and Laszlo Kovacs */
  4.  
  5. /*
  6. This module provides an interface to Berkeley socket IPC.
  7.  
  8. Limitations:
  9.  
  10. - only AF_INET and AF_UNIX address families are supported
  11. - no read/write operations (use send/recv or makefile instead)
  12. - additional restrictions apply on Windows
  13.  
  14. Module interface:
  15.  
  16. - socket.error: exception raised for socket specific errors
  17. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  18. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  19. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  20. - socket.getprotobyname(protocolname) --> protocol number
  21. - socket.getservbyname(servicename, protocolname) --> port number
  22. - socket.socket(family, type [, proto]) --> new socket object
  23. - socket.ntohs(16 bit value) --> new int object
  24. - socket.ntohl(32 bit value) --> new int object
  25. - socket.htons(16 bit value) --> new int object
  26. - socket.htonl(32 bit value) --> new int object
  27. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  28. - socket.inet_aton(IP address) -> 32-bit packed IP representation
  29. - socket.inet_ntoa(packed IP) -> IP address string
  30. - socket.ssl(socket, keyfile, certfile) -> new ssl object
  31. - an Internet socket address is a pair (hostname, port)
  32.   where hostname can be anything recognized by gethostbyname()
  33.   (including the dd.dd.dd.dd notation) and port is in host byte order
  34. - where a hostname is returned, the dd.dd.dd.dd notation is used
  35. - a UNIX domain socket address is a string specifying the pathname
  36.  
  37. Socket methods:
  38.  
  39. - s.accept() --> new socket object, sockaddr
  40. - s.bind(sockaddr) --> None
  41. - s.close() --> None
  42. - s.connect(sockaddr) --> None
  43. - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
  44. - s.fileno() --> file descriptor
  45. - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
  46. - s.getpeername() --> sockaddr
  47. - s.getsockname() --> sockaddr
  48. - s.getsockopt(level, optname[, buflen]) --> int or string
  49. - s.listen(backlog) --> None
  50. - s.makefile([mode[, bufsize]]) --> file object
  51. - s.recv(buflen [,flags]) --> string
  52. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  53. - s.send(string [,flags]) --> nbytes
  54. - s.sendto(string, [flags,] sockaddr) --> nbytes
  55. - s.setblocking(0 | 1) --> None
  56. - s.setsockopt(level, optname, value) --> None
  57. - s.shutdown(how) --> None
  58. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  59.  
  60. */
  61.  
  62. #include "Python.h"
  63.  
  64. /* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
  65.    script doesn't get this right, so we hardcode some platform checks below.
  66.    On the other hand, not all Linux versions agree, so there the settings
  67.    computed by the configure script are needed! */
  68.  
  69. #ifndef linux
  70. #undef HAVE_GETHOSTBYNAME_R_3_ARG
  71. #undef HAVE_GETHOSTBYNAME_R_5_ARG
  72. #undef HAVE_GETHOSTBYNAME_R_6_ARG
  73. #endif
  74.  
  75. #ifndef WITH_THREAD
  76. #undef HAVE_GETHOSTBYNAME_R
  77. #endif
  78.  
  79. #ifdef HAVE_GETHOSTBYNAME_R
  80. #if defined(_AIX) || defined(__osf__)
  81. #define HAVE_GETHOSTBYNAME_R_3_ARG
  82. #elif defined(__sun__) || defined(__sgi)
  83. #define HAVE_GETHOSTBYNAME_R_5_ARG
  84. #elif defined(linux)
  85. /* Rely on the configure script */
  86. #else
  87. #undef HAVE_GETHOSTBYNAME_R
  88. #endif
  89. #endif
  90.  
  91. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
  92. #define USE_GETHOSTBYNAME_LOCK
  93. #endif
  94.  
  95. #ifdef USE_GETHOSTBYNAME_LOCK
  96. #include "pythread.h"
  97. #endif
  98.  
  99. #ifdef HAVE_UNISTD_H
  100. #include <unistd.h>
  101. #endif
  102.  
  103. #if defined(PYCC_VACPP)
  104. #include <types.h>
  105. #include <io.h>
  106. #include <sys/ioctl.h>
  107. #include <utils.h>
  108. #include <ctype.h>
  109. #endif
  110.  
  111. #if defined(PYOS_OS2)
  112. #define  INCL_DOS
  113. #define  INCL_DOSERRORS
  114. #define  INCL_NOPMAPI
  115. #include <os2.h>
  116. #endif
  117.  
  118. #include <sys/types.h>
  119.  
  120. #include <signal.h>
  121. #ifndef MS_WINDOWS
  122. #ifdef HAVE_SYS_PARAM_H
  123. #include <sys/param.h>
  124. #endif
  125. #include <netdb.h>
  126. #include <sys/socket.h>
  127. #include <netinet/in.h>
  128. #ifndef __BEOS__
  129. #include <netinet/tcp.h>
  130. #endif
  131.  
  132. /* Headers needed for inet_ntoa() and inet_addr() */
  133. #ifdef __BEOS__
  134. #include <net/netdb.h>
  135. #else
  136. #ifndef USE_GUSI1
  137. #include <arpa/inet.h>
  138. #endif
  139. #endif
  140.  
  141. #include <fcntl.h>
  142. #else
  143. #include <winsock.h>
  144. #include <fcntl.h>
  145. #endif
  146. #if defined(AMITCP) || defined(INET225)
  147. #define SYS_TTYCHARS_H
  148. #include <sys/ioctl.h>
  149. #include <proto/socket.h>
  150. typedef LONG socklen_t;
  151. #endif
  152. #ifdef HAVE_SYS_UN_H
  153. #include <sys/un.h>
  154. #else
  155. #undef AF_UNIX
  156. #endif
  157.  
  158. #ifndef O_NDELAY
  159. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  160. #endif
  161.  
  162. #ifdef USE_GUSI1
  163. /* fdopen() isn't declared in stdio.h (sigh) */
  164. #include <GUSI.h>
  165. #endif
  166.  
  167. #ifdef USE_SSL
  168. #include "rsa.h"
  169. #include "crypto.h"
  170. #include "x509.h"
  171. #include "pem.h"
  172. #include "ssl.h"
  173. #include "err.h"
  174. #endif /* USE_SSL */
  175.  
  176. #if defined(MS_WINDOWS) || defined(__BEOS__)
  177. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  178. /* seem to be a few differences in the API */
  179. #define SOCKETCLOSE closesocket
  180. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  181. #endif
  182.  
  183. /* abstract the socket file descriptor type */
  184. #ifdef MS_WINDOWS
  185. typedef SOCKET SOCKET_T;
  186. #    ifdef MS_WIN64
  187. #        define SIZEOF_SOCKET_T 8
  188. #    else
  189. #        define SIZEOF_SOCKET_T 4
  190. #    endif
  191. #else
  192. typedef int SOCKET_T;
  193. #    define SIZEOF_SOCKET_T SIZEOF_INT
  194. #endif
  195.  
  196.  
  197. #if defined(PYOS_OS2)
  198. #define SOCKETCLOSE soclose
  199. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  200. #endif
  201.  
  202. #ifdef AMITCP
  203. /* seem to be a few differences in the API */
  204. //#define close CloseSocket
  205. #define ioctlsocket IoctlSocket
  206. #undef NO_DUP
  207. #undef AF_UNIX
  208. #endif
  209.  
  210. #ifdef INET225
  211. /* seem to be a few differences in the API */
  212. #define close s_close
  213. #define ioctlsocket s_ioctl
  214. #undef NO_DUP
  215. static __inline int dup(int oldsd) { return s_dup(oldsd); }
  216. #undef AF_UNIX
  217. #endif
  218.  
  219. #ifndef SOCKETCLOSE
  220. #define SOCKETCLOSE close
  221. #endif
  222.  
  223. /* Global variable holding the exception type for errors detected
  224.    by this module (but not argument type or memory errors, etc.). */
  225.  
  226. static PyObject *PySocket_Error;
  227.  
  228. #ifdef USE_SSL
  229. static PyObject *SSLErrorObject;
  230. #endif /* USE_SSL */
  231.  
  232.  
  233. /* Convenience function to raise an error according to errno
  234.    and return a NULL pointer from a function. */
  235.  
  236. static PyObject *
  237. PySocket_Err(void)
  238. {
  239. #ifdef MS_WINDOWS
  240.     int err_no = WSAGetLastError();
  241.     if (err_no) {
  242.         static struct { int no; const char *msg; } *msgp, msgs[] = {
  243.             { WSAEINTR, "Interrupted system call" },
  244.             { WSAEBADF, "Bad file descriptor" },
  245.             { WSAEACCES, "Permission denied" },
  246.             { WSAEFAULT, "Bad address" },
  247.             { WSAEINVAL, "Invalid argument" },
  248.             { WSAEMFILE, "Too many open files" },
  249.             { WSAEWOULDBLOCK, 
  250.                 "The socket operation could not complete "
  251.                 "without blocking" },
  252.             { WSAEINPROGRESS, "Operation now in progress" },
  253.             { WSAEALREADY, "Operation already in progress" },
  254.             { WSAENOTSOCK, "Socket operation on non-socket" },
  255.             { WSAEDESTADDRREQ, "Destination address required" },
  256.             { WSAEMSGSIZE, "Message too long" },
  257.             { WSAEPROTOTYPE, "Protocol wrong type for socket" },
  258.             { WSAENOPROTOOPT, "Protocol not available" },
  259.             { WSAEPROTONOSUPPORT, "Protocol not supported" },
  260.             { WSAESOCKTNOSUPPORT, "Socket type not supported" },
  261.             { WSAEOPNOTSUPP, "Operation not supported" },
  262.             { WSAEPFNOSUPPORT, "Protocol family not supported" },
  263.             { WSAEAFNOSUPPORT, "Address family not supported" },
  264.             { WSAEADDRINUSE, "Address already in use" },
  265.             { WSAEADDRNOTAVAIL,
  266.                 "Can't assign requested address" },
  267.             { WSAENETDOWN, "Network is down" },
  268.             { WSAENETUNREACH, "Network is unreachable" },
  269.             { WSAENETRESET, 
  270.                 "Network dropped connection on reset" },
  271.             { WSAECONNABORTED, 
  272.                 "Software caused connection abort" },
  273.             { WSAECONNRESET, "Connection reset by peer" },
  274.             { WSAENOBUFS, "No buffer space available" },
  275.             { WSAEISCONN, "Socket is already connected" },
  276.             { WSAENOTCONN, "Socket is not connected" },
  277.             { WSAESHUTDOWN, "Can't send after socket shutdown" },
  278.             { WSAETOOMANYREFS,
  279.                 "Too many references: can't splice" },
  280.             { WSAETIMEDOUT, "Operation timed out" },
  281.             { WSAECONNREFUSED, "Connection refused" },
  282.             { WSAELOOP, "Too many levels of symbolic links" },
  283.             { WSAENAMETOOLONG, "File name too long" },
  284.             { WSAEHOSTDOWN, "Host is down" },
  285.             { WSAEHOSTUNREACH, "No route to host" },
  286.             { WSAENOTEMPTY, "Directory not empty" },
  287.             { WSAEPROCLIM, "Too many processes" },
  288.             { WSAEUSERS, "Too many users" },
  289.             { WSAEDQUOT, "Disc quota exceeded" },
  290.             { WSAESTALE, "Stale NFS file handle" },
  291.             { WSAEREMOTE, "Too many levels of remote in path" },
  292.             { WSASYSNOTREADY,
  293.                 "Network subsystem is unvailable" },
  294.             { WSAVERNOTSUPPORTED,
  295.                 "WinSock version is not supported" },
  296.             { WSANOTINITIALISED, 
  297.                 "Successful WSAStartup() not yet performed" },
  298.             { WSAEDISCON, "Graceful shutdown in progress" },
  299.             /* Resolver errors */
  300.             { WSAHOST_NOT_FOUND, "No such host is known" },
  301.             { WSATRY_AGAIN, "Host not found, or server failed" },
  302.             { WSANO_RECOVERY,
  303.                 "Unexpected server error encountered" },
  304.             { WSANO_DATA, "Valid name without requested data" },
  305.             { WSANO_ADDRESS, "No address, look for MX record" },
  306.             { 0, NULL }
  307.         };
  308.         PyObject *v;
  309.         const char *msg = "winsock error";
  310.         
  311.         for (msgp = msgs; msgp->msg; msgp++) {
  312.             if (err_no == msgp->no) {
  313.                 msg = msgp->msg;
  314.                 break;
  315.             }
  316.         }
  317.  
  318.         v = Py_BuildValue("(is)", err_no, msg);
  319.         if (v != NULL) {
  320.             PyErr_SetObject(PySocket_Error, v);
  321.             Py_DECREF(v);
  322.         }
  323.         return NULL;
  324.     }
  325.     else
  326. #endif
  327.  
  328. #if defined(PYOS_OS2)
  329.     if (sock_errno() != NO_ERROR) {
  330.         APIRET rc;
  331.         ULONG  msglen;
  332.         char   outbuf[100];
  333.         int    myerrorcode = sock_errno();
  334.  
  335.         /* Retrieve Socket-Related Error Message from MPTN.MSG File */
  336.         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  337.                            myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
  338.         if (rc == NO_ERROR) {
  339.             PyObject *v;
  340.  
  341.             outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  342.             if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  343.                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
  344.                 while (lastc > outbuf && isspace(*lastc))
  345.                     *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  346.             }
  347.             v = Py_BuildValue("(is)", myerrorcode, outbuf);
  348.             if (v != NULL) {
  349.                 PyErr_SetObject(PySocket_Error, v);
  350.                 Py_DECREF(v);
  351.             }
  352.             return NULL;
  353.         }
  354.     }
  355. #endif
  356.  
  357.     return PyErr_SetFromErrno(PySocket_Error);
  358. }
  359.  
  360.  
  361. /* The object holding a socket.  It holds some extra information,
  362.    like the address family, which is used to decode socket address
  363.    arguments properly. */
  364.  
  365. typedef struct {
  366.     PyObject_HEAD
  367.     SOCKET_T sock_fd;        /* Socket file descriptor */
  368.     int sock_family;    /* Address family, e.g., AF_INET */
  369.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  370.     int sock_proto;        /* Protocol type, usually 0 */
  371.     union sock_addr {
  372.         struct sockaddr_in in;
  373. #ifdef AF_UNIX
  374.         struct sockaddr_un un;
  375. #endif
  376.     } sock_addr;
  377. } PySocketSockObject;
  378.  
  379. #ifdef USE_SSL
  380.  
  381. typedef struct {
  382.     PyObject_HEAD
  383.     PySocketSockObject *Socket;    /* Socket on which we're layered */
  384.     PyObject     *x_attr;    /* Attributes dictionary */
  385.     SSL_CTX*     ctx;
  386.     SSL*         ssl;
  387.     X509*        server_cert;
  388.     BIO*        sbio;
  389.     char        server[256];
  390.     char        issuer[256];
  391.  
  392. } SSLObject;
  393.  
  394. staticforward PyTypeObject SSL_Type;
  395. staticforward PyObject *SSL_SSLwrite(SSLObject *self, PyObject *args);
  396. staticforward PyObject *SSL_SSLread(SSLObject *self, PyObject *args);
  397.  
  398. #define SSLObject_Check(v)    ((v)->ob_type == &SSL_Type)
  399.  
  400. #endif /* USE_SSL */
  401.  
  402. /* A forward reference to the Socktype type object.
  403.    The Socktype variable contains pointers to various functions,
  404.    some of which call newsockobject(), which uses Socktype, so
  405.    there has to be a circular reference. */
  406.  
  407. staticforward PyTypeObject PySocketSock_Type;
  408.  
  409.  
  410. /* Create a new socket object.
  411.    This just creates the object and initializes it.
  412.    If the creation fails, return NULL and set an exception (implicit
  413.    in NEWOBJ()). */
  414.  
  415. static PySocketSockObject *
  416. PySocketSock_New(SOCKET_T fd, int family, int type, int proto)
  417. {
  418.     PySocketSockObject *s;
  419.     PySocketSock_Type.ob_type = &PyType_Type;
  420.     s = PyObject_New(PySocketSockObject, &PySocketSock_Type);
  421.     if (s != NULL) {
  422.         s->sock_fd = fd;
  423.         s->sock_family = family;
  424.         s->sock_type = type;
  425.         s->sock_proto = proto;
  426. #if defined(AMITCP) || defined (INET225)
  427.         /* Amiga's TCP stacks want a zeroed out sock_addr structure */
  428.         memset(&s->sock_addr, 0, sizeof(s->sock_addr));
  429. #ifdef AMITCP
  430.         if(family==AF_INET) s->sock_addr.in.sin_len=sizeof(struct sockaddr_in);
  431. #ifdef AF_UNIX
  432.         if(family==AF_UNIX) s->sock_addr.un.sun_len=sizeof(struct sockaddr_un);
  433. #endif /* AF_UNIX */
  434. #endif /* AMITCP */
  435. #endif /* AMITCP || INET225 */
  436.     }
  437.     return s;
  438. }
  439.  
  440.  
  441. /* Lock to allow python interpreter to continue, but only allow one 
  442.    thread to be in gethostbyname */
  443. #ifdef USE_GETHOSTBYNAME_LOCK
  444. PyThread_type_lock gethostbyname_lock;
  445. #endif
  446.  
  447.  
  448. /* Convert a string specifying a host name or one of a few symbolic
  449.    names to a numeric IP address.  This usually calls gethostbyname()
  450.    to do the work; the names "" and "<broadcast>" are special.
  451.    Return the length (should always be 4 bytes), or negative if
  452.    an error occurred; then an exception is raised. */
  453.  
  454. static int
  455. setipaddr(char* name, struct sockaddr_in * addr_ret)
  456. {
  457.     struct hostent *hp;
  458.     int d1, d2, d3, d4;
  459.     int h_length;
  460.     char ch;
  461. #ifdef HAVE_GETHOSTBYNAME_R
  462.     struct hostent hp_allocated;
  463. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  464.     struct hostent_data data;
  465. #else
  466.     char buf[1001];
  467.     int buf_len = (sizeof buf) - 1;
  468.     int errnop;
  469. #endif
  470. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  471.     int result;
  472. #endif
  473. #endif /* HAVE_GETHOSTBYNAME_R */
  474.  
  475.     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  476.     if (name[0] == '\0') {
  477.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  478.         return 4;
  479.     }
  480.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  481.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  482.         return 4;
  483.     }
  484.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  485.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  486.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  487.         addr_ret->sin_addr.s_addr = htonl(
  488.             ((long) d1 << 24) | ((long) d2 << 16) |
  489.             ((long) d3 << 8) | ((long) d4 << 0));
  490.         return 4;
  491.     }
  492.     Py_BEGIN_ALLOW_THREADS
  493. #ifdef HAVE_GETHOSTBYNAME_R
  494. #if    defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  495.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &hp, &errnop);
  496. #elif  defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  497.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  498. #else  /* HAVE_GETHOSTBYNAME_R_3_ARG */
  499.     memset((void *) &data, '\0', sizeof(data));
  500.     result = gethostbyname_r(name, &hp_allocated, &data);
  501.     hp = (result != 0) ? NULL : &hp_allocated;
  502. #endif
  503. #else /* not HAVE_GETHOSTBYNAME_R */
  504. #ifdef USE_GETHOSTBYNAME_LOCK
  505.     PyThread_acquire_lock(gethostbyname_lock, 1);
  506. #endif
  507.     hp = gethostbyname(name);
  508. #endif /* HAVE_GETHOSTBYNAME_R */
  509.     Py_END_ALLOW_THREADS
  510.  
  511.     if (hp == NULL) {
  512. #ifdef HAVE_HSTRERROR
  513.             /* Let's get real error message to return */
  514.             extern int h_errno;
  515.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  516. #else
  517.         PyErr_SetString(PySocket_Error, "host not found");
  518. #endif
  519. #ifdef USE_GETHOSTBYNAME_LOCK
  520.         PyThread_release_lock(gethostbyname_lock);
  521. #endif
  522.         return -1;
  523.     }
  524.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  525.     h_length = hp->h_length;
  526. #ifdef USE_GETHOSTBYNAME_LOCK
  527.     PyThread_release_lock(gethostbyname_lock);
  528. #endif
  529.     return h_length;
  530. }
  531.  
  532.  
  533. /* Create a string object representing an IP address.
  534.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  535.    size numbers). */
  536.  
  537. static PyObject *
  538. makeipaddr(struct sockaddr_in *addr)
  539. {
  540.     long x = ntohl(addr->sin_addr.s_addr);
  541.     char buf[100];
  542.     sprintf(buf, "%d.%d.%d.%d",
  543.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  544.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  545.     return PyString_FromString(buf);
  546. }
  547.  
  548.  
  549. /* Create an object representing the given socket address,
  550.    suitable for passing it back to bind(), connect() etc.
  551.    The family field of the sockaddr structure is inspected
  552.    to determine what kind of address it really is. */
  553.  
  554. /*ARGSUSED*/
  555. static PyObject *
  556. makesockaddr(struct sockaddr *addr, int addrlen)
  557. {
  558.     if (addrlen == 0) {
  559.         /* No address -- may be recvfrom() from known socket */
  560.         Py_INCREF(Py_None);
  561.         return Py_None;
  562.     }
  563.  
  564. #ifdef __BEOS__
  565.     /* XXX: BeOS version of accept() doesn't set family correctly */
  566.     addr->sa_family = AF_INET;
  567. #endif
  568.  
  569.     switch (addr->sa_family) {
  570.  
  571.     case AF_INET:
  572.     {
  573.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  574.         PyObject *addrobj = makeipaddr(a);
  575.         PyObject *ret = NULL;
  576.         if (addrobj) {
  577.             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  578.             Py_DECREF(addrobj);
  579.         }
  580.         return ret;
  581.     }
  582.  
  583. #ifdef AF_UNIX
  584.     case AF_UNIX:
  585.     {
  586.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  587.         return PyString_FromString(a->sun_path);
  588.     }
  589. #endif /* AF_UNIX */
  590.  
  591.     /* More cases here... */
  592.  
  593.     default:
  594.         /* If we don't know the address family, don't raise an
  595.            exception -- return it as a tuple. */
  596.         return Py_BuildValue("is#",
  597.                      addr->sa_family,
  598.                      addr->sa_data,
  599.                      sizeof(addr->sa_data));
  600.  
  601.     }
  602. }
  603.  
  604.  
  605. /* Parse a socket address argument according to the socket object's
  606.    address family.  Return 1 if the address was in the proper format,
  607.    0 of not.  The address is returned through addr_ret, its length
  608.    through len_ret. */
  609.  
  610. static int
  611. getsockaddrarg(PySocketSockObject *s, PyObject *args, struct sockaddr **addr_ret, int *len_ret)
  612. {
  613.     switch (s->sock_family) {
  614.  
  615. #ifdef AF_UNIX
  616.     case AF_UNIX:
  617.     {
  618.         struct sockaddr_un* addr;
  619.         char *path;
  620.         int len;
  621.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  622.         if (!PyArg_Parse(args, "t#", &path, &len))
  623.             return 0;
  624.         if (len > sizeof addr->sun_path) {
  625.             PyErr_SetString(PySocket_Error,
  626.                     "AF_UNIX path too long");
  627.             return 0;
  628.         }
  629.         addr->sun_family = AF_UNIX;
  630.         memcpy(addr->sun_path, path, len);
  631.         addr->sun_path[len] = 0;
  632.         *addr_ret = (struct sockaddr *) addr;
  633.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  634.         return 1;
  635.     }
  636. #endif /* AF_UNIX */
  637.  
  638.     case AF_INET:
  639.     {
  640.         struct sockaddr_in* addr;
  641.         char *host;
  642.         int port;
  643.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  644.         if (!PyArg_Parse(args, "(si)", &host, &port))
  645.             return 0;
  646.         if (setipaddr(host, addr) < 0)
  647.             return 0;
  648.         addr->sin_family = AF_INET;
  649.         addr->sin_port = htons((short)port);
  650.         *addr_ret = (struct sockaddr *) addr;
  651.         *len_ret = sizeof *addr;
  652.         return 1;
  653.     }
  654.  
  655.     /* More cases here... */
  656.  
  657.     default:
  658.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  659.         return 0;
  660.  
  661.     }
  662. }
  663.  
  664.  
  665. /* Get the address length according to the socket object's address family. 
  666.    Return 1 if the family is known, 0 otherwise.  The length is returned
  667.    through len_ret. */
  668.  
  669. static int
  670. getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
  671. {
  672.     switch (s->sock_family) {
  673.  
  674. #ifdef AF_UNIX
  675.     case AF_UNIX:
  676.     {
  677.         *len_ret = sizeof (struct sockaddr_un);
  678.         return 1;
  679.     }
  680. #endif /* AF_UNIX */
  681.  
  682.     case AF_INET:
  683.     {
  684.         *len_ret = sizeof (struct sockaddr_in);
  685.         return 1;
  686.     }
  687.  
  688.     /* More cases here... */
  689.  
  690.     default:
  691.         PyErr_SetString(PySocket_Error, "getsockaddrlen: bad family");
  692.         return 0;
  693.  
  694.     }
  695. }
  696.  
  697.  
  698. /* s.accept() method */
  699.  
  700. static PyObject *
  701. PySocketSock_accept(PySocketSockObject *s, PyObject *args)
  702. {
  703.     char addrbuf[256];
  704.     SOCKET_T newfd;
  705.     socklen_t addrlen;
  706.     PyObject *sock = NULL;
  707.     PyObject *addr = NULL;
  708.     PyObject *res = NULL;
  709.  
  710.     if (!PyArg_ParseTuple(args, ":accept"))
  711.         return NULL;
  712.     if (!getsockaddrlen(s, &addrlen))
  713.         return NULL;
  714.     Py_BEGIN_ALLOW_THREADS
  715.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  716.     Py_END_ALLOW_THREADS
  717. #ifdef MS_WINDOWS
  718.     if (newfd == INVALID_SOCKET)
  719. #else
  720.     if (newfd < 0)
  721. #endif
  722.         return PySocket_Err();
  723.  
  724.     /* Create the new object with unspecified family,
  725.        to avoid calls to bind() etc. on it. */
  726.     sock = (PyObject *) PySocketSock_New(newfd,
  727.                     s->sock_family,
  728.                     s->sock_type,
  729.                     s->sock_proto);
  730.     if (sock == NULL) {
  731.         SOCKETCLOSE(newfd);
  732.         goto finally;
  733.     }
  734.     if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
  735.         goto finally;
  736.  
  737.     if (!(res = Py_BuildValue("OO", sock, addr)))
  738.         goto finally;
  739.  
  740.   finally:
  741.     Py_XDECREF(sock);
  742.     Py_XDECREF(addr);
  743.     return res;
  744. }
  745.  
  746. static char accept_doc[] =
  747. "accept() -> (socket object, address info)\n\
  748. \n\
  749. Wait for an incoming connection.  Return a new socket representing the\n\
  750. connection, and the address of the client.  For IP sockets, the address\n\
  751. info is a pair (hostaddr, port).";
  752.  
  753.  
  754. /* s.setblocking(1 | 0) method */
  755.  
  756. static PyObject *
  757. PySocketSock_setblocking(PySocketSockObject *s, PyObject *args)
  758. {
  759.     int block;
  760. #ifndef MS_WINDOWS
  761.     int delay_flag;
  762. #endif
  763.     if (!PyArg_ParseTuple(args, "i:setblocking", &block))
  764.         return NULL;
  765.     Py_BEGIN_ALLOW_THREADS
  766. #ifdef __BEOS__
  767.     block = !block;
  768.     setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  769.                 (void *)(&block), sizeof( int ) );
  770. #else
  771. #ifndef MS_WINDOWS
  772. #ifdef PYOS_OS2
  773.     block = !block;
  774.     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  775. #else /* !PYOS_OS2 */
  776.  #if defined(AMITCP) || defined (INET225)
  777.     block = !block;
  778.     ioctlsocket(s->sock_fd, FIONBIO, &block);
  779.  #else
  780.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  781.     if (block)
  782.         delay_flag &= (~O_NDELAY);
  783.     else
  784.         delay_flag |= O_NDELAY;
  785.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  786.  #endif /* !AMITCP || INET225 */
  787. #endif /* !PYOS_OS2 */
  788. #else /* MS_WINDOWS */
  789.     block = !block;
  790.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  791. #endif /* MS_WINDOWS */
  792. #endif /* __BEOS__ */
  793.     Py_END_ALLOW_THREADS
  794.  
  795.     Py_INCREF(Py_None);
  796.     return Py_None;
  797. }
  798.  
  799. static char setblocking_doc[] =
  800. "setblocking(flag)\n\
  801. \n\
  802. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  803. This uses the FIONBIO ioctl with the O_NDELAY flag.";
  804.  
  805.  
  806. /* s.setsockopt() method.
  807.    With an integer third argument, sets an integer option.
  808.    With a string third argument, sets an option from a buffer;
  809.    use optional built-in module 'struct' to encode the string. */
  810.  
  811. static PyObject *
  812. PySocketSock_setsockopt(PySocketSockObject *s, PyObject *args)
  813. {
  814.     int level;
  815.     int optname;
  816.     int res;
  817.     char *buf;
  818.     int buflen;
  819.     int flag;
  820.  
  821.     if (PyArg_ParseTuple(args, "iii:setsockopt",
  822.                  &level, &optname, &flag)) {
  823.         buf = (char *) &flag;
  824.         buflen = sizeof flag;
  825.     }
  826.     else {
  827.         PyErr_Clear();
  828.         if (!PyArg_ParseTuple(args, "iis#:setsockopt",
  829.                       &level, &optname, &buf, &buflen))
  830.             return NULL;
  831.     }
  832.     res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
  833.     if (res < 0)
  834.         return PySocket_Err();
  835.     Py_INCREF(Py_None);
  836.     return Py_None;
  837. }
  838.  
  839. static char setsockopt_doc[] =
  840. "setsockopt(level, option, value)\n\
  841. \n\
  842. Set a socket option.  See the Unix manual for level and option.\n\
  843. The value argument can either be an integer or a string.";
  844.  
  845.  
  846. /* s.getsockopt() method.
  847.    With two arguments, retrieves an integer option.
  848.    With a third integer argument, retrieves a string buffer of that size;
  849.    use optional built-in module 'struct' to decode the string. */
  850.  
  851. static PyObject *
  852. PySocketSock_getsockopt(PySocketSockObject *s, PyObject *args)
  853. {
  854.     int level;
  855.     int optname;
  856.     int res;
  857.     PyObject *buf;
  858.     socklen_t buflen = 0;
  859.  
  860. #ifdef __BEOS__
  861. /* We have incomplete socket support. */
  862.     PyErr_SetString( PySocket_Error, "getsockopt not supported" );
  863.     return NULL;
  864. #else
  865.  
  866.     if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
  867.                   &level, &optname, &buflen))
  868.         return NULL;
  869.     
  870.     if (buflen == 0) {
  871.         int flag = 0;
  872.         socklen_t flagsize = sizeof flag;
  873.         res = getsockopt(s->sock_fd, level, optname,
  874.                  (void *)&flag, &flagsize);
  875.         if (res < 0)
  876.             return PySocket_Err();
  877.         return PyInt_FromLong(flag);
  878.     }
  879.     if (buflen <= 0 || buflen > 1024) {
  880.         PyErr_SetString(PySocket_Error,
  881.                 "getsockopt buflen out of range");
  882.         return NULL;
  883.     }
  884.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  885.     if (buf == NULL)
  886.         return NULL;
  887.     res = getsockopt(s->sock_fd, level, optname,
  888.              (void *)PyString_AsString(buf), &buflen);
  889.     if (res < 0) {
  890.         Py_DECREF(buf);
  891.         return PySocket_Err();
  892.     }
  893.     _PyString_Resize(&buf, buflen);
  894.     return buf;
  895. #endif /* __BEOS__ */
  896. }
  897.  
  898. static char getsockopt_doc[] =
  899. "getsockopt(level, option[, buffersize]) -> value\n\
  900. \n\
  901. Get a socket option.  See the Unix manual for level and option.\n\
  902. If a nonzero buffersize argument is given, the return value is a\n\
  903. string of that length; otherwise it is an integer.";
  904.  
  905.  
  906. /* s.bind(sockaddr) method */
  907.  
  908. static PyObject *
  909. PySocketSock_bind(PySocketSockObject *s, PyObject *args)
  910. {
  911.     struct sockaddr *addr;
  912.     int addrlen;
  913.     int res;
  914.     PyObject *addro;
  915.     if (!PyArg_ParseTuple(args, "O:bind", &addro))
  916.         return NULL;
  917.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  918.         return NULL;
  919.     Py_BEGIN_ALLOW_THREADS
  920.     res = bind(s->sock_fd, addr, addrlen);
  921.     Py_END_ALLOW_THREADS
  922.     if (res < 0)
  923.         return PySocket_Err();
  924.     Py_INCREF(Py_None);
  925.     return Py_None;
  926. }
  927.  
  928. static char bind_doc[] =
  929. "bind(address)\n\
  930. \n\
  931. Bind the socket to a local address.  For IP sockets, the address is a\n\
  932. pair (host, port); the host must refer to the local host.";
  933.  
  934.  
  935. /* s.close() method.
  936.    Set the file descriptor to -1 so operations tried subsequently
  937.    will surely fail. */
  938.  
  939. static PyObject *
  940. PySocketSock_close(PySocketSockObject *s, PyObject *args)
  941. {
  942.     if (!PyArg_ParseTuple(args, ":close"))
  943.         return NULL;
  944.     if (s->sock_fd != -1) {
  945.         Py_BEGIN_ALLOW_THREADS
  946.         (void) SOCKETCLOSE(s->sock_fd);
  947.         Py_END_ALLOW_THREADS
  948.     }
  949.     s->sock_fd = -1;
  950.     Py_INCREF(Py_None);
  951.     return Py_None;
  952. }
  953.  
  954. static char close_doc[] =
  955. "close()\n\
  956. \n\
  957. Close the socket.  It cannot be used after this call.";
  958.  
  959.  
  960. /* s.connect(sockaddr) method */
  961.  
  962. static PyObject *
  963. PySocketSock_connect(PySocketSockObject *s, PyObject *args)
  964. {
  965.     struct sockaddr *addr;
  966.     int addrlen;
  967.     int res;
  968.     PyObject *addro;
  969.     if (!PyArg_ParseTuple(args, "O:connect", &addro))
  970.         return NULL;
  971.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  972.         return NULL;
  973.     Py_BEGIN_ALLOW_THREADS
  974.     res = connect(s->sock_fd, addr, addrlen);
  975.     Py_END_ALLOW_THREADS
  976.     if (res < 0)
  977.         return PySocket_Err();
  978.     Py_INCREF(Py_None);
  979.     return Py_None;
  980. }
  981.  
  982. static char connect_doc[] =
  983. "connect(address)\n\
  984. \n\
  985. Connect the socket to a remote address.  For IP sockets, the address\n\
  986. is a pair (host, port).";
  987.  
  988.  
  989. /* s.connect_ex(sockaddr) method */
  990.  
  991. static PyObject *
  992. PySocketSock_connect_ex(PySocketSockObject *s, PyObject *args)
  993. {
  994.     struct sockaddr *addr;
  995.     int addrlen;
  996.     int res;
  997.     PyObject *addro;
  998.     if (!PyArg_ParseTuple(args, "O:connect_ex", &addro))
  999.         return NULL;
  1000.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1001.         return NULL;
  1002.     Py_BEGIN_ALLOW_THREADS
  1003.     res = connect(s->sock_fd, addr, addrlen);
  1004.     Py_END_ALLOW_THREADS
  1005.     if (res != 0)
  1006.         res = errno;
  1007.     return PyInt_FromLong((long) res);
  1008. }
  1009.  
  1010. static char connect_ex_doc[] =
  1011. "connect_ex(address)\n\
  1012. \n\
  1013. This is like connect(address), but returns an error code (the errno value)\n\
  1014. instead of raising an exception when an error occurs.";
  1015.  
  1016.  
  1017. /* s.fileno() method */
  1018.  
  1019. static PyObject *
  1020. PySocketSock_fileno(PySocketSockObject *s, PyObject *args)
  1021. {
  1022.     if (!PyArg_ParseTuple(args, ":fileno"))
  1023.         return NULL;
  1024. #if SIZEOF_SOCKET_T <= SIZEOF_LONG
  1025.     return PyInt_FromLong((long) s->sock_fd);
  1026. #else
  1027.     return PyLong_FromLongLong((LONG_LONG)s->sock_fd);
  1028. #endif
  1029. }
  1030.  
  1031. static char fileno_doc[] =
  1032. "fileno() -> integer\n\
  1033. \n\
  1034. Return the integer file descriptor of the socket.";
  1035.  
  1036.  
  1037. #ifndef NO_DUP
  1038. /* s.dup() method */
  1039.  
  1040. static PyObject *
  1041. PySocketSock_dup(PySocketSockObject *s, PyObject *args)
  1042. {
  1043.     SOCKET_T newfd;
  1044.     PyObject *sock;
  1045.     if (!PyArg_ParseTuple(args, ":dup"))
  1046.         return NULL;
  1047.     newfd = dup(s->sock_fd);
  1048.     if (newfd < 0)
  1049.         return PySocket_Err();
  1050.     sock = (PyObject *) PySocketSock_New(newfd,
  1051.                          s->sock_family,
  1052.                          s->sock_type,
  1053.                          s->sock_proto);
  1054.     if (sock == NULL)
  1055.         SOCKETCLOSE(newfd);
  1056.     return sock;
  1057. }
  1058.  
  1059. static char dup_doc[] =
  1060. "dup() -> socket object\n\
  1061. \n\
  1062. Return a new socket object connected to the same system resource.";
  1063.  
  1064. #endif
  1065.  
  1066.  
  1067. /* s.getsockname() method */
  1068.  
  1069. static PyObject *
  1070. PySocketSock_getsockname(PySocketSockObject *s, PyObject *args)
  1071. {
  1072.     char addrbuf[256];
  1073.     int res;
  1074.     socklen_t addrlen;
  1075.  
  1076.     if (!PyArg_ParseTuple(args, ":getsockname"))
  1077.         return NULL;
  1078.     if (!getsockaddrlen(s, &addrlen))
  1079.         return NULL;
  1080.     memset(addrbuf, 0, addrlen);
  1081.     Py_BEGIN_ALLOW_THREADS
  1082.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  1083.     Py_END_ALLOW_THREADS
  1084.     if (res < 0)
  1085.         return PySocket_Err();
  1086.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  1087. }
  1088.  
  1089. static char getsockname_doc[] =
  1090. "getsockname() -> address info\n\
  1091. \n\
  1092. Return the address of the local endpoint.  For IP sockets, the address\n\
  1093. info is a pair (hostaddr, port).";
  1094.  
  1095.  
  1096. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  1097. /* s.getpeername() method */
  1098.  
  1099. static PyObject *
  1100. PySocketSock_getpeername(PySocketSockObject *s, PyObject *args)
  1101. {
  1102.     char addrbuf[256];
  1103.     int res;
  1104.     socklen_t addrlen;
  1105.  
  1106.     if (!PyArg_ParseTuple(args, ":getpeername"))
  1107.         return NULL;
  1108.     if (!getsockaddrlen(s, &addrlen))
  1109.         return NULL;
  1110.     Py_BEGIN_ALLOW_THREADS
  1111.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  1112.     Py_END_ALLOW_THREADS
  1113.     if (res < 0)
  1114.         return PySocket_Err();
  1115.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  1116. }
  1117.  
  1118. static char getpeername_doc[] =
  1119. "getpeername() -> address info\n\
  1120. \n\
  1121. Return the address of the remote endpoint.  For IP sockets, the address\n\
  1122. info is a pair (hostaddr, port).";
  1123.  
  1124. #endif /* HAVE_GETPEERNAME */
  1125.  
  1126.  
  1127. /* s.listen(n) method */
  1128.  
  1129. static PyObject *
  1130. PySocketSock_listen(PySocketSockObject *s, PyObject *args)
  1131. {
  1132.     int backlog;
  1133.     int res;
  1134.     if (!PyArg_ParseTuple(args, "i:listen", &backlog))
  1135.         return NULL;
  1136.     Py_BEGIN_ALLOW_THREADS
  1137.     if (backlog < 1)
  1138.         backlog = 1;
  1139.     res = listen(s->sock_fd, backlog);
  1140.     Py_END_ALLOW_THREADS
  1141.     if (res < 0)
  1142.         return PySocket_Err();
  1143.     Py_INCREF(Py_None);
  1144.     return Py_None;
  1145. }
  1146.  
  1147. static char listen_doc[] =
  1148. "listen(backlog)\n\
  1149. \n\
  1150. Enable a server to accept connections.  The backlog argument must be at\n\
  1151. least 1; it specifies the number of unaccepted connection that the system\n\
  1152. will allow before refusing new connections.";
  1153.  
  1154.  
  1155. #ifndef NO_DUP
  1156. /* s.makefile(mode) method.
  1157.    Create a new open file object referring to a dupped version of
  1158.    the socket's file descriptor.  (The dup() call is necessary so
  1159.    that the open file and socket objects may be closed independent
  1160.    of each other.)
  1161.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  1162.  
  1163. static PyObject *
  1164. PySocketSock_makefile(PySocketSockObject *s, PyObject *args)
  1165. {
  1166.     extern int fclose(FILE *);
  1167.     char *mode = "r";
  1168.     int bufsize = -1;
  1169. #ifdef MS_WIN32
  1170.     intptr_t fd;
  1171. #else
  1172.     int fd;
  1173. #endif    
  1174.     FILE *fp;
  1175.     PyObject *f;
  1176.  
  1177.     if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
  1178.         return NULL;
  1179. #ifdef MS_WIN32
  1180.     if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
  1181.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
  1182. #else
  1183.     if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
  1184. #endif
  1185.     {
  1186.         if (fd >= 0)
  1187.             SOCKETCLOSE(fd);
  1188.         return PySocket_Err();
  1189.     }
  1190.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  1191.     if (f != NULL)
  1192.         PyFile_SetBufSize(f, bufsize);
  1193.     return f;
  1194. }
  1195.  
  1196. static char makefile_doc[] =
  1197. "makefile([mode[, buffersize]]) -> file object\n\
  1198. \n\
  1199. Return a regular file object corresponding to the socket.\n\
  1200. The mode and buffersize arguments are as for the built-in open() function.";
  1201.  
  1202. #endif /* NO_DUP */
  1203.  
  1204.  
  1205. /* s.recv(nbytes [,flags]) method */
  1206.  
  1207. static PyObject *
  1208. PySocketSock_recv(PySocketSockObject *s, PyObject *args)
  1209. {
  1210.     int len, n, flags = 0;
  1211.     PyObject *buf;
  1212.     if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags))
  1213.         return NULL;
  1214.     buf = PyString_FromStringAndSize((char *) 0, len);
  1215.     if (buf == NULL)
  1216.         return NULL;
  1217.     Py_BEGIN_ALLOW_THREADS
  1218.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  1219.     Py_END_ALLOW_THREADS
  1220.     if (n < 0) {
  1221.         Py_DECREF(buf);
  1222.         return PySocket_Err();
  1223.     }
  1224.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1225.         return NULL;
  1226.     return buf;
  1227. }
  1228.  
  1229. static char recv_doc[] =
  1230. "recv(buffersize[, flags]) -> data\n\
  1231. \n\
  1232. Receive up to buffersize bytes from the socket.  For the optional flags\n\
  1233. argument, see the Unix manual.  When no data is available, block until\n\
  1234. at least one byte is available or until the remote end is closed.  When\n\
  1235. the remote end is closed and all data is read, return the empty string.";
  1236.  
  1237.  
  1238. /* s.recvfrom(nbytes [,flags]) method */
  1239.  
  1240. static PyObject *
  1241. PySocketSock_recvfrom(PySocketSockObject *s, PyObject *args)
  1242. {
  1243.     char addrbuf[256];
  1244.     PyObject *buf = NULL;
  1245.     PyObject *addr = NULL;
  1246.     PyObject *ret = NULL;
  1247.  
  1248.     int len, n, flags = 0;
  1249.     socklen_t addrlen;
  1250.     if (!PyArg_ParseTuple(args, "i|i:recvfrom", &len, &flags))
  1251.         return NULL;
  1252.     if (!getsockaddrlen(s, &addrlen))
  1253.         return NULL;
  1254.     buf = PyString_FromStringAndSize((char *) 0, len);
  1255.     if (buf == NULL)
  1256.         return NULL;
  1257.     Py_BEGIN_ALLOW_THREADS
  1258.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  1259. #ifndef MS_WINDOWS
  1260. #if defined(PYOS_OS2)
  1261.              (struct sockaddr *)addrbuf, &addrlen
  1262. #else
  1263.              (void *)addrbuf, &addrlen
  1264. #endif
  1265. #else
  1266.              (struct sockaddr *)addrbuf, &addrlen
  1267. #endif
  1268.              );
  1269.     Py_END_ALLOW_THREADS
  1270.     if (n < 0) {
  1271.         Py_DECREF(buf);
  1272.         return PySocket_Err();
  1273.     }
  1274.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1275.         return NULL;
  1276.         
  1277.     if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
  1278.         goto finally;
  1279.  
  1280.     ret = Py_BuildValue("OO", buf, addr);
  1281.   finally:
  1282.     Py_XDECREF(addr);
  1283.     Py_XDECREF(buf);
  1284.     return ret;
  1285. }
  1286.  
  1287. static char recvfrom_doc[] =
  1288. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  1289. \n\
  1290. Like recv(buffersize, flags) but also return the sender's address info.";
  1291.  
  1292.  
  1293. /* s.send(data [,flags]) method */
  1294.  
  1295. static PyObject *
  1296. PySocketSock_send(PySocketSockObject *s, PyObject *args)
  1297. {
  1298.     char *buf;
  1299.     int len, n, flags = 0;
  1300.     if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
  1301.         return NULL;
  1302.     Py_BEGIN_ALLOW_THREADS
  1303.     n = send(s->sock_fd, buf, len, flags);
  1304.     Py_END_ALLOW_THREADS
  1305.     if (n < 0)
  1306.         return PySocket_Err();
  1307.     return PyInt_FromLong((long)n);
  1308. }
  1309.  
  1310. static char send_doc[] =
  1311. "send(data[, flags])\n\
  1312. \n\
  1313. Send a data string to the socket.  For the optional flags\n\
  1314. argument, see the Unix manual.";
  1315.  
  1316.  
  1317. /* s.sendto(data, [flags,] sockaddr) method */
  1318.  
  1319. static PyObject *
  1320. PySocketSock_sendto(PySocketSockObject *s, PyObject *args)
  1321. {
  1322.     PyObject *addro;
  1323.     char *buf;
  1324.     struct sockaddr *addr;
  1325.     int addrlen, len, n, flags;
  1326.     flags = 0;
  1327.     if (!PyArg_ParseTuple(args, "s#O:sendto", &buf, &len, &addro)) {
  1328.         PyErr_Clear();
  1329.         if (!PyArg_ParseTuple(args, "s#iO:sendto",
  1330.                       &buf, &len, &flags, &addro))
  1331.             return NULL;
  1332.     }
  1333.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1334.         return NULL;
  1335.     Py_BEGIN_ALLOW_THREADS
  1336.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  1337.     Py_END_ALLOW_THREADS
  1338.     if (n < 0)
  1339.         return PySocket_Err();
  1340.     return PyInt_FromLong((long)n);
  1341. }
  1342.  
  1343. static char sendto_doc[] =
  1344. "sendto(data[, flags], address)\n\
  1345. \n\
  1346. Like send(data, flags) but allows specifying the destination address.\n\
  1347. For IP sockets, the address is a pair (hostaddr, port).";
  1348.  
  1349.  
  1350. /* s.shutdown(how) method */
  1351.  
  1352. static PyObject *
  1353. PySocketSock_shutdown(PySocketSockObject *s, PyObject *args)
  1354. {
  1355.     int how;
  1356.     int res;
  1357.     if (!PyArg_ParseTuple(args, "i:shutdown", &how))
  1358.         return NULL;
  1359.     Py_BEGIN_ALLOW_THREADS
  1360.     res = shutdown(s->sock_fd, how);
  1361.     Py_END_ALLOW_THREADS
  1362.     if (res < 0)
  1363.         return PySocket_Err();
  1364.     Py_INCREF(Py_None);
  1365.     return Py_None;
  1366. }
  1367.  
  1368. static char shutdown_doc[] =
  1369. "shutdown(flag)\n\
  1370. \n\
  1371. Shut down the reading side of the socket (flag == 0), the writing side\n\
  1372. of the socket (flag == 1), or both ends (flag == 2).";
  1373.  
  1374.  
  1375. /* List of methods for socket objects */
  1376.  
  1377. static PyMethodDef PySocketSock_methods[] = {
  1378.     {"accept",        (PyCFunction)PySocketSock_accept, METH_VARARGS,
  1379.                 accept_doc},
  1380.     {"bind",        (PyCFunction)PySocketSock_bind, METH_VARARGS,
  1381.                 bind_doc},
  1382.     {"close",        (PyCFunction)PySocketSock_close, METH_VARARGS,
  1383.                 close_doc},
  1384.     {"connect",        (PyCFunction)PySocketSock_connect, METH_VARARGS,
  1385.                 connect_doc},
  1386.     {"connect_ex",        (PyCFunction)PySocketSock_connect_ex, METH_VARARGS,
  1387.                 connect_ex_doc},
  1388. #ifndef NO_DUP
  1389.     {"dup",            (PyCFunction)PySocketSock_dup, METH_VARARGS,
  1390.                 dup_doc},
  1391. #endif
  1392.     {"fileno",        (PyCFunction)PySocketSock_fileno, METH_VARARGS,
  1393.                 fileno_doc},
  1394. #ifdef HAVE_GETPEERNAME
  1395.     {"getpeername",        (PyCFunction)PySocketSock_getpeername, METH_VARARGS,
  1396.                 getpeername_doc},
  1397. #endif
  1398.     {"getsockname",        (PyCFunction)PySocketSock_getsockname, METH_VARARGS,
  1399.                 getsockname_doc},
  1400.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, METH_VARARGS,
  1401.                 getsockopt_doc},
  1402.     {"listen",        (PyCFunction)PySocketSock_listen, METH_VARARGS,
  1403.                 listen_doc},
  1404. #ifndef NO_DUP
  1405.     {"makefile",        (PyCFunction)PySocketSock_makefile, METH_VARARGS,
  1406.                 makefile_doc},
  1407. #endif
  1408.     {"recv",        (PyCFunction)PySocketSock_recv, METH_VARARGS,
  1409.                 recv_doc},
  1410.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, METH_VARARGS,
  1411.                 recvfrom_doc},
  1412.     {"send",        (PyCFunction)PySocketSock_send, METH_VARARGS,
  1413.                 send_doc},
  1414.     {"sendto",        (PyCFunction)PySocketSock_sendto, METH_VARARGS,
  1415.                 sendto_doc},
  1416.     {"setblocking",        (PyCFunction)PySocketSock_setblocking, METH_VARARGS,
  1417.                 setblocking_doc},
  1418.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt, METH_VARARGS,
  1419.                 setsockopt_doc},
  1420.     {"shutdown",        (PyCFunction)PySocketSock_shutdown, METH_VARARGS,
  1421.                 shutdown_doc},
  1422.     {NULL,            NULL}        /* sentinel */
  1423. };
  1424.  
  1425.  
  1426. /* Deallocate a socket object in response to the last Py_DECREF().
  1427.    First close the file description. */
  1428.  
  1429. static void
  1430. PySocketSock_dealloc(PySocketSockObject *s)
  1431. {
  1432.     if (s->sock_fd != -1)
  1433.         (void) SOCKETCLOSE(s->sock_fd);
  1434.     PyObject_Del(s);
  1435. }
  1436.  
  1437.  
  1438. /* Return a socket object's named attribute. */
  1439.  
  1440. static PyObject *
  1441. PySocketSock_getattr(PySocketSockObject *s, char *name)
  1442. {
  1443.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  1444. }
  1445.  
  1446.  
  1447. static PyObject *
  1448. PySocketSock_repr(PySocketSockObject *s)
  1449. {
  1450.     char buf[512];
  1451. #if SIZEOF_SOCKET_T > SIZEOF_LONG
  1452.     if (s->sock_fd > LONG_MAX) {
  1453.         /* this can occur on Win64, and actually there is a special
  1454.            ugly printf formatter for decimal pointer length integer
  1455.            printing, only bother if necessary*/
  1456.         PyErr_SetString(PyExc_OverflowError,
  1457.             "no printf formatter to display the socket descriptor in decimal");
  1458.         return NULL;
  1459.     }
  1460. #endif
  1461.     sprintf(buf, 
  1462.         "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>", 
  1463.         (long)s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  1464.     return PyString_FromString(buf);
  1465. }
  1466.  
  1467.  
  1468. /* Type object for socket objects. */
  1469.  
  1470. static PyTypeObject PySocketSock_Type = {
  1471.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1472.     0,
  1473.     "socket",
  1474.     sizeof(PySocketSockObject),
  1475.     0,
  1476.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1477.     0,        /*tp_print*/
  1478.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1479.     0,        /*tp_setattr*/
  1480.     0,        /*tp_compare*/
  1481.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1482.     0,        /*tp_as_number*/
  1483.     0,        /*tp_as_sequence*/
  1484.     0,        /*tp_as_mapping*/
  1485. };
  1486.  
  1487.  
  1488. /* Python interface to gethostname(). */
  1489.  
  1490. /*ARGSUSED*/
  1491. static PyObject *
  1492. PySocket_gethostname(PyObject *self, PyObject *args)
  1493. {
  1494.     char buf[1024];
  1495.     int res;
  1496.     if (!PyArg_ParseTuple(args, ":gethostname"))
  1497.         return NULL;
  1498.     Py_BEGIN_ALLOW_THREADS
  1499.     res = gethostname(buf, (int) sizeof buf - 1);
  1500.     Py_END_ALLOW_THREADS
  1501.     if (res < 0)
  1502.         return PySocket_Err();
  1503.     buf[sizeof buf - 1] = '\0';
  1504.     return PyString_FromString(buf);
  1505. }
  1506.  
  1507. static char gethostname_doc[] =
  1508. "gethostname() -> string\n\
  1509. \n\
  1510. Return the current host name.";
  1511.  
  1512.  
  1513. /* Python interface to gethostbyname(name). */
  1514.  
  1515. /*ARGSUSED*/
  1516. static PyObject *
  1517. PySocket_gethostbyname(PyObject *self, PyObject *args)
  1518. {
  1519.     char *name;
  1520.     struct sockaddr_in addrbuf;
  1521.     if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
  1522.         return NULL;
  1523.     if (setipaddr(name, &addrbuf) < 0)
  1524.         return NULL;
  1525.     return makeipaddr(&addrbuf);
  1526. }
  1527.  
  1528. static char gethostbyname_doc[] =
  1529. "gethostbyname(host) -> address\n\
  1530. \n\
  1531. Return the IP address (a string of the form '255.255.255.255') for a host.";
  1532.  
  1533.  
  1534. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  1535.  
  1536. static PyObject *
  1537. gethost_common(struct hostent *h, struct sockaddr_in *addr)
  1538. {
  1539.     char **pch;
  1540.     PyObject *rtn_tuple = (PyObject *)NULL;
  1541.     PyObject *name_list = (PyObject *)NULL;
  1542.     PyObject *addr_list = (PyObject *)NULL;
  1543.     PyObject *tmp;
  1544.     if (h == NULL) {
  1545. #ifdef HAVE_HSTRERROR
  1546.             /* Let's get real error message to return */
  1547.             extern int h_errno;
  1548.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1549. #else
  1550.         PyErr_SetString(PySocket_Error, "host not found");
  1551. #endif
  1552.         return NULL;
  1553.     }
  1554.     if ((name_list = PyList_New(0)) == NULL)
  1555.         goto err;
  1556.     if ((addr_list = PyList_New(0)) == NULL)
  1557.         goto err;
  1558.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1559.         int status;
  1560.         tmp = PyString_FromString(*pch);
  1561.         if (tmp == NULL)
  1562.             goto err;
  1563.         status = PyList_Append(name_list, tmp);
  1564.         Py_DECREF(tmp);
  1565.         if (status)
  1566.             goto err;
  1567.     }
  1568.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1569.         int status;
  1570.         memcpy((char *) &addr->sin_addr, *pch, h->h_length);
  1571.         tmp = makeipaddr(addr);
  1572.         if (tmp == NULL)
  1573.             goto err;
  1574.         status = PyList_Append(addr_list, tmp);
  1575.         Py_DECREF(tmp);
  1576.         if (status)
  1577.             goto err;
  1578.     }
  1579.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1580.  err:
  1581.     Py_XDECREF(name_list);
  1582.     Py_XDECREF(addr_list);
  1583.     return rtn_tuple;
  1584. }
  1585.  
  1586.  
  1587. /* Python interface to gethostbyname_ex(name). */
  1588.  
  1589. /*ARGSUSED*/
  1590. static PyObject *
  1591. PySocket_gethostbyname_ex(PyObject *self, PyObject *args)
  1592. {
  1593.     char *name;
  1594.     struct hostent *h;
  1595.     struct sockaddr_in addr;
  1596.     PyObject *ret;
  1597. #ifdef HAVE_GETHOSTBYNAME_R
  1598.     struct hostent hp_allocated;
  1599. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1600.     struct hostent_data data;
  1601. #else
  1602.     char buf[16384];
  1603.     int buf_len = (sizeof buf) - 1;
  1604.     int errnop;
  1605. #endif
  1606. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1607.     int result;
  1608. #endif
  1609. #endif /* HAVE_GETHOSTBYNAME_R */
  1610.     if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
  1611.         return NULL;
  1612.     if (setipaddr(name, &addr) < 0)
  1613.         return NULL;
  1614.     Py_BEGIN_ALLOW_THREADS
  1615. #ifdef HAVE_GETHOSTBYNAME_R
  1616. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1617.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &h, &errnop);
  1618. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1619.     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  1620. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1621.     memset((void *) &data, '\0', sizeof(data));
  1622.     result = gethostbyname_r(name, &hp_allocated, &data);
  1623.     h = (result != 0) ? NULL : &hp_allocated;
  1624. #endif
  1625. #else /* not HAVE_GETHOSTBYNAME_R */
  1626. #ifdef USE_GETHOSTBYNAME_LOCK
  1627.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1628. #endif
  1629.     h = gethostbyname(name);
  1630. #endif /* HAVE_GETHOSTBYNAME_R */
  1631.     Py_END_ALLOW_THREADS
  1632.     ret = gethost_common(h, &addr);
  1633. #ifdef USE_GETHOSTBYNAME_LOCK
  1634.     PyThread_release_lock(gethostbyname_lock);
  1635. #endif
  1636.     return ret;
  1637. }
  1638.  
  1639. static char ghbn_ex_doc[] =
  1640. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  1641. \n\
  1642. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1643. for a host.  The host argument is a string giving a host name or IP number.";
  1644.  
  1645.  
  1646. /* Python interface to gethostbyaddr(IP). */
  1647.  
  1648. /*ARGSUSED*/
  1649. static PyObject *
  1650. PySocket_gethostbyaddr(PyObject *self, PyObject *args)
  1651. {
  1652.         struct sockaddr_in addr;
  1653.     char *ip_num;
  1654.     struct hostent *h;
  1655.     PyObject *ret;
  1656. #ifdef HAVE_GETHOSTBYNAME_R
  1657.     struct hostent hp_allocated;
  1658. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1659.     struct hostent_data data;
  1660. #else
  1661.     char buf[16384];
  1662.     int buf_len = (sizeof buf) - 1;
  1663.     int errnop;
  1664. #endif
  1665. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1666.     int result;
  1667. #endif
  1668. #endif /* HAVE_GETHOSTBYNAME_R */
  1669.  
  1670.     if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
  1671.         return NULL;
  1672.     if (setipaddr(ip_num, &addr) < 0)
  1673.         return NULL;
  1674.     Py_BEGIN_ALLOW_THREADS
  1675. #ifdef HAVE_GETHOSTBYNAME_R
  1676. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1677.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1678.         sizeof(addr.sin_addr),
  1679.         AF_INET, &hp_allocated, buf, buf_len,
  1680.         &h, &errnop);
  1681. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1682.     h = gethostbyaddr_r((char *)&addr.sin_addr,
  1683.                 sizeof(addr.sin_addr),
  1684.                 AF_INET, 
  1685.                 &hp_allocated, buf, buf_len, &errnop);
  1686. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1687.     memset((void *) &data, '\0', sizeof(data));
  1688.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1689.         sizeof(addr.sin_addr),
  1690.         AF_INET, &hp_allocated, &data);
  1691.     h = (result != 0) ? NULL : &hp_allocated;
  1692. #endif
  1693. #else /* not HAVE_GETHOSTBYNAME_R */
  1694. #ifdef USE_GETHOSTBYNAME_LOCK
  1695.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1696. #endif
  1697.     h = gethostbyaddr((char *)&addr.sin_addr,
  1698.               sizeof(addr.sin_addr),
  1699.               AF_INET);
  1700. #endif /* HAVE_GETHOSTBYNAME_R */
  1701.     Py_END_ALLOW_THREADS
  1702.     ret = gethost_common(h, &addr);
  1703. #ifdef USE_GETHOSTBYNAME_LOCK
  1704.     PyThread_release_lock(gethostbyname_lock);
  1705. #endif
  1706.     return ret;
  1707. }
  1708.  
  1709. static char gethostbyaddr_doc[] =
  1710. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  1711. \n\
  1712. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1713. for a host.  The host argument is a string giving a host name or IP number.";
  1714.  
  1715.  
  1716. /* Python interface to getservbyname(name).
  1717.    This only returns the port number, since the other info is already
  1718.    known or not useful (like the list of aliases). */
  1719.  
  1720. /*ARGSUSED*/
  1721. static PyObject *
  1722. PySocket_getservbyname(PyObject *self, PyObject *args)
  1723. {
  1724.     char *name, *proto;
  1725.     struct servent *sp;
  1726.     if (!PyArg_ParseTuple(args, "ss:getservbyname", &name, &proto))
  1727.         return NULL;
  1728.     Py_BEGIN_ALLOW_THREADS
  1729.     sp = getservbyname(name, proto);
  1730.     Py_END_ALLOW_THREADS
  1731.     if (sp == NULL) {
  1732.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1733.         return NULL;
  1734.     }
  1735.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1736. }
  1737.  
  1738. static char getservbyname_doc[] =
  1739. "getservbyname(servicename, protocolname) -> integer\n\
  1740. \n\
  1741. Return a port number from a service name and protocol name.\n\
  1742. The protocol name should be 'tcp' or 'udp'.";
  1743.  
  1744.  
  1745. /* Python interface to getprotobyname(name).
  1746.    This only returns the protocol number, since the other info is
  1747.    already known or not useful (like the list of aliases). */
  1748.  
  1749. /*ARGSUSED*/
  1750. static PyObject *
  1751. PySocket_getprotobyname(PyObject *self, PyObject *args)
  1752. {
  1753.     char *name;
  1754.     struct protoent *sp;
  1755. #ifdef __BEOS__
  1756. /* Not available in BeOS yet. - [cjh] */
  1757.     PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
  1758.     return NULL;
  1759. #else
  1760.     if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
  1761.         return NULL;
  1762.     Py_BEGIN_ALLOW_THREADS
  1763.     sp = getprotobyname(name);
  1764.     Py_END_ALLOW_THREADS
  1765.     if (sp == NULL) {
  1766.         PyErr_SetString(PySocket_Error, "protocol not found");
  1767.         return NULL;
  1768.     }
  1769.     return PyInt_FromLong((long) sp->p_proto);
  1770. #endif
  1771. }
  1772.  
  1773. static char getprotobyname_doc[] =
  1774. "getprotobyname(name) -> integer\n\
  1775. \n\
  1776. Return the protocol number for the named protocol.  (Rarely used.)";
  1777.  
  1778.  
  1779. /* Python interface to socket(family, type, proto).
  1780.    The third (protocol) argument is optional.
  1781.    Return a new socket object. */
  1782.  
  1783. /*ARGSUSED*/
  1784. static PyObject *
  1785. PySocket_socket(PyObject *self, PyObject *args)
  1786. {
  1787.     PySocketSockObject *s;
  1788.     SOCKET_T fd;
  1789.     int family, type, proto = 0;
  1790.     if (!PyArg_ParseTuple(args, "ii|i:socket", &family, &type, &proto))
  1791.         return NULL;
  1792.     Py_BEGIN_ALLOW_THREADS
  1793.     fd = socket(family, type, proto);
  1794.     Py_END_ALLOW_THREADS
  1795. #ifdef MS_WINDOWS
  1796.     if (fd == INVALID_SOCKET)
  1797. #else
  1798.     if (fd < 0)
  1799. #endif
  1800.         return PySocket_Err();
  1801.     s = PySocketSock_New(fd, family, type, proto);
  1802.     /* If the object can't be created, don't forget to close the
  1803.        file descriptor again! */
  1804.     if (s == NULL)
  1805.         (void) SOCKETCLOSE(fd);
  1806.     /* From now on, ignore SIGPIPE and let the error checking
  1807.        do the work. */
  1808. #ifdef SIGPIPE      
  1809.     (void) signal(SIGPIPE, SIG_IGN);
  1810. #endif   
  1811.     return (PyObject *) s;
  1812. }
  1813.  
  1814. static char socket_doc[] =
  1815. "socket(family, type[, proto]) -> socket object\n\
  1816. \n\
  1817. Open a socket of the given type.  The family argument specifies the\n\
  1818. address family; it is normally AF_INET, sometimes AF_UNIX.\n\
  1819. The type argument specifies whether this is a stream (SOCK_STREAM)\n\
  1820. or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
  1821. specifying the default protocol.";
  1822.  
  1823.  
  1824. #ifndef NO_DUP
  1825. /* Create a socket object from a numeric file description.
  1826.    Useful e.g. if stdin is a socket.
  1827.    Additional arguments as for socket(). */
  1828.  
  1829. /*ARGSUSED*/
  1830. static PyObject *
  1831. PySocket_fromfd(PyObject *self, PyObject *args)
  1832. {
  1833.     PySocketSockObject *s;
  1834.     SOCKET_T fd;
  1835.     int family, type, proto = 0;
  1836.     if (!PyArg_ParseTuple(args, "iii|i:fromfd",
  1837.                   &fd, &family, &type, &proto))
  1838.         return NULL;
  1839.     /* Dup the fd so it and the socket can be closed independently */
  1840.     fd = dup(fd);
  1841.     if (fd < 0)
  1842.         return PySocket_Err();
  1843.     s = PySocketSock_New(fd, family, type, proto);
  1844.     /* From now on, ignore SIGPIPE and let the error checking
  1845.        do the work. */
  1846. #ifdef SIGPIPE      
  1847.     (void) signal(SIGPIPE, SIG_IGN);
  1848. #endif   
  1849.     return (PyObject *) s;
  1850. }
  1851.  
  1852. static char fromfd_doc[] =
  1853. "fromfd(fd, family, type[, proto]) -> socket object\n\
  1854. \n\
  1855. Create a socket object from the given file descriptor.\n\
  1856. The remaining arguments are the same as for socket().";
  1857.  
  1858. #endif /* NO_DUP */
  1859.  
  1860.  
  1861. static PyObject *
  1862. PySocket_ntohs(PyObject *self, PyObject *args)
  1863. {
  1864.     int x1, x2;
  1865.  
  1866.     if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
  1867.         return NULL;
  1868.     }
  1869.     x2 = (int)ntohs((short)x1);
  1870.     return PyInt_FromLong(x2);
  1871. }
  1872.  
  1873. static char ntohs_doc[] =
  1874. "ntohs(integer) -> integer\n\
  1875. \n\
  1876. Convert a 16-bit integer from network to host byte order.";
  1877.  
  1878.  
  1879. static PyObject *
  1880. PySocket_ntohl(PyObject *self, PyObject *args)
  1881. {
  1882.     int x1, x2;
  1883.  
  1884.     if (!PyArg_ParseTuple(args, "i:ntohl", &x1)) {
  1885.         return NULL;
  1886.     }
  1887.     x2 = ntohl(x1);
  1888.     return PyInt_FromLong(x2);
  1889. }
  1890.  
  1891. static char ntohl_doc[] =
  1892. "ntohl(integer) -> integer\n\
  1893. \n\
  1894. Convert a 32-bit integer from network to host byte order.";
  1895.  
  1896.  
  1897. static PyObject *
  1898. PySocket_htons(PyObject *self, PyObject *args)
  1899. {
  1900.     int x1, x2;
  1901.  
  1902.     if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
  1903.         return NULL;
  1904.     }
  1905.     x2 = (int)htons((short)x1);
  1906.     return PyInt_FromLong(x2);
  1907. }
  1908.  
  1909. static char htons_doc[] =
  1910. "htons(integer) -> integer\n\
  1911. \n\
  1912. Convert a 16-bit integer from host to network byte order.";
  1913.  
  1914.  
  1915. static PyObject *
  1916. PySocket_htonl(PyObject *self, PyObject *args)
  1917. {
  1918.     int x1, x2;
  1919.  
  1920.     if (!PyArg_ParseTuple(args, "i:htonl", &x1)) {
  1921.         return NULL;
  1922.     }
  1923.     x2 = htonl(x1);
  1924.     return PyInt_FromLong(x2);
  1925. }
  1926.  
  1927. static char htonl_doc[] =
  1928. "htonl(integer) -> integer\n\
  1929. \n\
  1930. Convert a 32-bit integer from host to network byte order.";
  1931.  
  1932. /*
  1933.  * socket.inet_aton() and socket.inet_ntoa() functions
  1934.  *
  1935.  * written 20 Aug 1999 by Ben Gertzfield <che@debian.org> <- blame him!
  1936.  *
  1937.  */
  1938.  
  1939. static char inet_aton_doc[] = 
  1940. "inet_aton(string) -> packed 32-bit IP representation\n\
  1941. \n\
  1942. Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
  1943. binary format used in low-level network functions.";
  1944.  
  1945. static PyObject*
  1946. PySocket_inet_aton(PyObject *self, PyObject *args)
  1947. {
  1948. #ifndef INADDR_NONE
  1949. #define INADDR_NONE (-1)
  1950. #endif
  1951.  
  1952.     /* Have to use inet_addr() instead */
  1953.     char *ip_addr;
  1954.     long packed_addr;
  1955.  
  1956.     if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) {
  1957.         return NULL;
  1958.     }
  1959. #ifdef USE_GUSI1
  1960.     packed_addr = (long)inet_addr(ip_addr).s_addr;
  1961. #else
  1962.     packed_addr = inet_addr(ip_addr);
  1963. #endif
  1964.  
  1965.     if (packed_addr == INADDR_NONE) {    /* invalid address */
  1966.         PyErr_SetString(PySocket_Error,
  1967.             "illegal IP address string passed to inet_aton");
  1968.         return NULL;
  1969.     }
  1970.  
  1971.     return PyString_FromStringAndSize((char *) &packed_addr,
  1972.                       sizeof(packed_addr));
  1973. }
  1974.  
  1975. static char inet_ntoa_doc[] = 
  1976. "inet_ntoa(packed_ip) -> ip_address_string\n\
  1977. \n\
  1978. Convert an IP address from 32-bit packed binary format to string format";
  1979.  
  1980. static PyObject*
  1981. PySocket_inet_ntoa(PyObject *self, PyObject *args)
  1982. {
  1983.     char *packed_str;
  1984.     int addr_len;
  1985.     struct in_addr packed_addr;
  1986.  
  1987.     if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
  1988.         return NULL;
  1989.     }
  1990.     
  1991.     if (addr_len != sizeof(packed_addr)) {
  1992.         PyErr_SetString(PySocket_Error,
  1993.             "packed IP wrong length for inet_ntoa");
  1994.         return NULL;
  1995.     }
  1996.  
  1997.     memcpy(&packed_addr, packed_str, addr_len);
  1998.  
  1999.     return PyString_FromString(inet_ntoa(packed_addr));
  2000. }
  2001.  
  2002.  
  2003. #ifdef USE_SSL
  2004.  
  2005. /* This is a C function to be called for new object initialization */
  2006. static SSLObject *
  2007. newSSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file)
  2008. {
  2009.     SSLObject *self;
  2010.  
  2011.     self = PyObject_New(SSLObject, &SSL_Type); /* Create new object */
  2012.     if (self == NULL){
  2013.         PyErr_SetObject(SSLErrorObject,
  2014.                 PyString_FromString("newSSLObject error"));
  2015.         return NULL;
  2016.     }
  2017.     memset(self->server, '\0', sizeof(char) * 256);
  2018.     memset(self->issuer, '\0', sizeof(char) * 256);  
  2019.   
  2020.     self->x_attr = PyDict_New();
  2021.     self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
  2022.     if (self->ctx == NULL) {
  2023.         PyErr_SetObject(SSLErrorObject,
  2024.                 PyString_FromString("SSL_CTX_new error"));
  2025.         PyObject_Del(self);
  2026.         return NULL;
  2027.     }
  2028.  
  2029.     if ( (key_file && !cert_file) || (!key_file && cert_file) )
  2030.     {
  2031.         PyErr_SetObject(SSLErrorObject,
  2032.               PyString_FromString(
  2033.             "Both the key & certificate files must be specified"));
  2034.         PyObject_Del(self);
  2035.         return NULL;
  2036.     }
  2037.  
  2038.     if (key_file && cert_file)
  2039.     {
  2040.         if (SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
  2041.                         SSL_FILETYPE_PEM) < 1)
  2042.         {
  2043.             PyErr_SetObject(SSLErrorObject,
  2044.                 PyString_FromString(
  2045.                   "SSL_CTX_use_PrivateKey_file error"));
  2046.             PyObject_Del(self);
  2047.             return NULL;
  2048.         }
  2049.  
  2050.         if (SSL_CTX_use_certificate_chain_file(self->ctx,
  2051.                                cert_file) < 1)
  2052.         {
  2053.             PyErr_SetObject(SSLErrorObject,
  2054.                 PyString_FromString(
  2055.                   "SSL_CTX_use_certificate_chain_file error"));
  2056.             PyObject_Del(self);
  2057.             return NULL;
  2058.         }
  2059.     }
  2060.  
  2061.     SSL_CTX_set_verify(self->ctx,
  2062.                SSL_VERIFY_NONE, NULL); /* set verify lvl */
  2063.     self->ssl = SSL_new(self->ctx); /* New ssl struct */
  2064.     SSL_set_fd(self->ssl, Sock->sock_fd);    /* Set the socket for SSL */
  2065.     SSL_set_connect_state(self->ssl);
  2066.  
  2067.     if ((SSL_connect(self->ssl)) == -1) {
  2068.         /* Actually negotiate SSL connection */
  2069.         PyErr_SetObject(SSLErrorObject,
  2070.                 PyString_FromString("SSL_connect error"));
  2071.         PyObject_Del(self);
  2072.         return NULL;
  2073.     }
  2074.     self->ssl->debug = 1;
  2075.  
  2076.     if ((self->server_cert = SSL_get_peer_certificate(self->ssl))) {
  2077.         X509_NAME_oneline(X509_get_subject_name(self->server_cert),
  2078.                   self->server, 256);
  2079.         X509_NAME_oneline(X509_get_issuer_name(self->server_cert),
  2080.                   self->issuer, 256);
  2081.     }
  2082.     self->x_attr = NULL;
  2083.     self->Socket = Sock;
  2084.     Py_INCREF(self->Socket);
  2085.     return self;
  2086. }
  2087.  
  2088. /* This is the Python function called for new object initialization */
  2089. static PyObject *
  2090. PySocket_ssl(PyObject *self, PyObject *args)
  2091. {
  2092.     SSLObject *rv;
  2093.     PySocketSockObject *Sock;
  2094.     char *key_file;
  2095.     char *cert_file;
  2096.   
  2097.     if (!PyArg_ParseTuple(args, "O!zz:ssl",
  2098.                   &PySocketSock_Type, (PyObject*)&Sock,
  2099.                   &key_file, &cert_file) )
  2100.         return NULL;
  2101.   
  2102.     rv = newSSLObject(Sock, key_file, cert_file);
  2103.     if ( rv == NULL )
  2104.         return NULL;
  2105.     return (PyObject *)rv;
  2106. }
  2107.  
  2108. static char ssl_doc[] =
  2109. "ssl(socket, keyfile, certfile) -> sslobject";
  2110.  
  2111. static PyObject *
  2112. SSL_server(SSLObject *self, PyObject *args)
  2113. {
  2114.     return PyString_FromString(self->server);
  2115. }
  2116.  
  2117. static PyObject *
  2118. SSL_issuer(SSLObject *self, PyObject *args)
  2119. {
  2120.     return PyString_FromString(self->issuer);
  2121. }
  2122.  
  2123.  
  2124. /* SSL object methods */
  2125.  
  2126. static PyMethodDef SSLMethods[] = {
  2127.     { "write", (PyCFunction)SSL_SSLwrite, 1 },
  2128.     { "read", (PyCFunction)SSL_SSLread, 1 },
  2129.     { "server", (PyCFunction)SSL_server, 1 },
  2130.     { "issuer", (PyCFunction)SSL_issuer, 1 },
  2131.     { NULL, NULL}
  2132. };
  2133.  
  2134. static void SSL_dealloc(SSLObject *self)
  2135. {
  2136.     if (self->server_cert)    /* Possible not to have one? */
  2137.         X509_free (self->server_cert);
  2138.     SSL_CTX_free(self->ctx);
  2139.     SSL_free(self->ssl);
  2140.     Py_XDECREF(self->x_attr);
  2141.     Py_XDECREF(self->Socket);
  2142.     PyObject_Del(self);
  2143. }
  2144.  
  2145. static PyObject *SSL_getattr(SSLObject *self, char *name)
  2146. {
  2147.     return Py_FindMethod(SSLMethods, (PyObject *)self, name);
  2148. }
  2149.  
  2150. staticforward PyTypeObject SSL_Type = {
  2151.     PyObject_HEAD_INIT(&PyType_Type)
  2152.     0,                /*ob_size*/
  2153.     "SSL",            /*tp_name*/
  2154.     sizeof(SSLObject),        /*tp_basicsize*/
  2155.     0,                /*tp_itemsize*/
  2156.     /* methods */
  2157.     (destructor)SSL_dealloc,    /*tp_dealloc*/
  2158.     0,                /*tp_print*/
  2159.     (getattrfunc)SSL_getattr,    /*tp_getattr*/
  2160.     0,                /*tp_setattr*/
  2161.     0,                /*tp_compare*/
  2162.     0,                /*tp_repr*/
  2163.     0,                /*tp_as_number*/
  2164.     0,                /*tp_as_sequence*/
  2165.     0,                /*tp_as_mapping*/
  2166.     0,                /*tp_hash*/
  2167. };
  2168.  
  2169.  
  2170.  
  2171. static PyObject *SSL_SSLwrite(SSLObject *self, PyObject *args)
  2172. {
  2173.     char *data;
  2174.     size_t len = 0;
  2175.   
  2176.     if (!PyArg_ParseTuple(args, "s|i:write", &data, &len))
  2177.         return NULL;
  2178.   
  2179.     if (!len)
  2180.         len = strlen(data);
  2181.   
  2182.     len = SSL_write(self->ssl, data, len);
  2183.     return PyInt_FromLong((long)len);
  2184. }
  2185.  
  2186. static PyObject *SSL_SSLread(SSLObject *self, PyObject *args)
  2187. {
  2188.     PyObject *buf;
  2189.     int count = 0;
  2190.     int len = 1024;
  2191.     int res;
  2192.   
  2193.     PyArg_ParseTuple(args, "|i:read", &len);
  2194.   
  2195.     if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
  2196.         return NULL;    /* Error object should already be set */
  2197.   
  2198.     count = SSL_read(self->ssl, PyString_AsString(buf), len);
  2199.     res = SSL_get_error(self->ssl, count);
  2200.  
  2201.     switch (res) {
  2202.     case 0:            /* Good return value! */
  2203.         break;
  2204.     case 6:
  2205.         PyErr_SetString(SSLErrorObject, "EOF");
  2206.         Py_DECREF(buf);
  2207.         return NULL;
  2208.         break;
  2209.     case 5:
  2210.     default:
  2211.         return PyErr_SetFromErrno(SSLErrorObject);
  2212.         break;
  2213.     }
  2214.   
  2215.     fflush(stderr);
  2216.       
  2217.     if (count < 0) {
  2218.         Py_DECREF(buf);
  2219.         return PyErr_SetFromErrno(SSLErrorObject);
  2220.     }
  2221.   
  2222.     if (count != len && _PyString_Resize(&buf, count) < 0)
  2223.         return NULL;
  2224.     return buf;
  2225. }
  2226.  
  2227. #endif /* USE_SSL */
  2228.  
  2229.  
  2230. /* List of functions exported by this module. */
  2231.  
  2232. static PyMethodDef PySocket_methods[] = {
  2233.     {"gethostbyname",    PySocket_gethostbyname, 
  2234.      METH_VARARGS, gethostbyname_doc},
  2235.     {"gethostbyname_ex",    PySocket_gethostbyname_ex, 
  2236.      METH_VARARGS, ghbn_ex_doc},
  2237.     {"gethostbyaddr",    PySocket_gethostbyaddr, 
  2238.      METH_VARARGS, gethostbyaddr_doc},
  2239.     {"gethostname",        PySocket_gethostname, 
  2240.      METH_VARARGS, gethostname_doc},
  2241.     {"getservbyname",    PySocket_getservbyname, 
  2242.      METH_VARARGS, getservbyname_doc},
  2243.     {"getprotobyname",    PySocket_getprotobyname, 
  2244.      METH_VARARGS,getprotobyname_doc},
  2245.     {"socket",        PySocket_socket, 
  2246.      METH_VARARGS, socket_doc},
  2247. #ifndef NO_DUP
  2248.     {"fromfd",        PySocket_fromfd, 
  2249.      METH_VARARGS, fromfd_doc},
  2250. #endif
  2251.     {"ntohs",        PySocket_ntohs, 
  2252.      METH_VARARGS, ntohs_doc},
  2253.     {"ntohl",        PySocket_ntohl, 
  2254.      METH_VARARGS, ntohl_doc},
  2255.     {"htons",        PySocket_htons, 
  2256.      METH_VARARGS, htons_doc},
  2257.     {"htonl",        PySocket_htonl, 
  2258.      METH_VARARGS, htonl_doc},
  2259.     {"inet_aton",        PySocket_inet_aton, 
  2260.      METH_VARARGS, inet_aton_doc},
  2261.     {"inet_ntoa",        PySocket_inet_ntoa, 
  2262.      METH_VARARGS, inet_ntoa_doc},
  2263. #ifdef USE_SSL
  2264.     {"ssl",            PySocket_ssl, 
  2265.      METH_VARARGS, ssl_doc},
  2266. #endif /* USE_SSL */
  2267.     {NULL,            NULL}         /* Sentinel */
  2268. };
  2269.  
  2270.  
  2271. /* Convenience routine to export an integer value.
  2272.  *
  2273.  * Errors are silently ignored, for better or for worse...
  2274.  */
  2275. static void
  2276. insint(PyObject *d, char *name, int value)
  2277. {
  2278.     PyObject *v = PyInt_FromLong((long) value);
  2279.     if (!v || PyDict_SetItemString(d, name, v))
  2280.         PyErr_Clear();
  2281.  
  2282.     Py_XDECREF(v);
  2283. }
  2284.  
  2285.  
  2286. #ifdef MS_WINDOWS
  2287.  
  2288. /* Additional initialization and cleanup for NT/Windows */
  2289.  
  2290. static void
  2291. NTcleanup(void)
  2292. {
  2293.     WSACleanup();
  2294. }
  2295.  
  2296. static int
  2297. NTinit(void)
  2298. {
  2299.     WSADATA WSAData;
  2300.     int ret;
  2301.     char buf[100];
  2302.     ret = WSAStartup(0x0101, &WSAData);
  2303.     switch (ret) {
  2304.     case 0:    /* no error */
  2305.         atexit(NTcleanup);
  2306.         return 1;
  2307.     case WSASYSNOTREADY:
  2308.         PyErr_SetString(PyExc_ImportError,
  2309.                 "WSAStartup failed: network not ready");
  2310.         break;
  2311.     case WSAVERNOTSUPPORTED:
  2312.     case WSAEINVAL:
  2313.         PyErr_SetString(PyExc_ImportError,
  2314.             "WSAStartup failed: requested version not supported");
  2315.         break;
  2316.     default:
  2317.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  2318.         PyErr_SetString(PyExc_ImportError, buf);
  2319.         break;
  2320.     }
  2321.     return 0;
  2322. }
  2323.  
  2324. #endif /* MS_WINDOWS */
  2325.  
  2326. #if defined(PYOS_OS2)
  2327.  
  2328. /* Additional initialization and cleanup for OS/2 */
  2329.  
  2330. static void
  2331. OS2cleanup(void)
  2332. {
  2333.     /* No cleanup is necessary for OS/2 Sockets */
  2334. }
  2335.  
  2336. static int
  2337. OS2init(void)
  2338. {
  2339.     char reason[64];
  2340.     int rc = sock_init();
  2341.  
  2342.     if (rc == 0) {
  2343.         atexit(OS2cleanup);
  2344.         return 1; /* Indicate Success */
  2345.     }
  2346.  
  2347.     sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
  2348.     PyErr_SetString(PyExc_ImportError, reason);
  2349.  
  2350.     return 0;  /* Indicate Failure */
  2351. }
  2352.  
  2353. #endif /* PYOS_OS2 */
  2354.  
  2355. /* Initialize this module.
  2356.  *   This is called when the first 'import socket' is done,
  2357.  *   via a table in config.c, if config.c is compiled with USE_SOCKET
  2358.  *   defined.
  2359.  *
  2360.  *   For MS_WINDOWS (which means any Windows variant), this module
  2361.  *   is actually called "_socket", and there's a wrapper "socket.py"
  2362.  *   which implements some missing functionality (such as makefile(),
  2363.  *   dup() and fromfd()).  The import of "_socket" may fail with an
  2364.  *   ImportError exception if initialization of WINSOCK fails.  When
  2365.  *   WINSOCK is initialized succesfully, a call to WSACleanup() is
  2366.  *   scheduled to be made at exit time.
  2367.  *
  2368.  *   For OS/2, this module is also called "_socket" and uses a wrapper
  2369.  *   "socket.py" which implements that functionality that is missing
  2370.  *   when PC operating systems don't put socket descriptors in the
  2371.  *   operating system's filesystem layer.
  2372.  */
  2373.  
  2374. static char module_doc[] =
  2375. "This module provides socket operations and some related functions.\n\
  2376. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.\n\
  2377. On other systems, it only supports IP.\n\
  2378. \n\
  2379. Functions:\n\
  2380. \n\
  2381. socket() -- create a new socket object\n\
  2382. fromfd() -- create a socket object from an open file descriptor (*)\n\
  2383. gethostname() -- return the current hostname\n\
  2384. gethostbyname() -- map a hostname to its IP number\n\
  2385. gethostbyaddr() -- map an IP number or hostname to DNS info\n\
  2386. getservbyname() -- map a service name and a protocol name to a port number\n\
  2387. getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number\n\
  2388. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\n\
  2389. htons(), htonl() -- convert 16, 32 bit int from host to network byte order\n\
  2390. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format\n\
  2391. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)\n\
  2392. ssl() -- secure socket layer support (only available if configured)\n\
  2393. \n\
  2394. (*) not available on all platforms!)\n\
  2395. \n\
  2396. Special objects:\n\
  2397. \n\
  2398. SocketType -- type object for socket objects\n\
  2399. error -- exception raised for I/O errors\n\
  2400. \n\
  2401. Integer constants:\n\
  2402. \n\
  2403. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)\n\
  2404. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\
  2405. \n\
  2406. Many other constants may be defined; these may be used in calls to\n\
  2407. the setsockopt() and getsockopt() methods.\n\
  2408. ";
  2409.  
  2410. static char sockettype_doc[] =
  2411. "A socket represents one endpoint of a network connection.\n\
  2412. \n\
  2413. Methods:\n\
  2414. \n\
  2415. accept() -- accept a connection, returning new socket and client address\n\
  2416. bind() -- bind the socket to a local address\n\
  2417. close() -- close the socket\n\
  2418. connect() -- connect the socket to a remote address\n\
  2419. connect_ex() -- connect, return an error code instead of an exception \n\
  2420. dup() -- return a new socket object identical to the current one (*)\n\
  2421. fileno() -- return underlying file descriptor\n\
  2422. getpeername() -- return remote address (*)\n\
  2423. getsockname() -- return local address\n\
  2424. getsockopt() -- get socket options\n\
  2425. listen() -- start listening for incoming connections\n\
  2426. makefile() -- return a file object corresponding tot the socket (*)\n\
  2427. recv() -- receive data\n\
  2428. recvfrom() -- receive data and sender's address\n\
  2429. send() -- send data\n\
  2430. sendto() -- send data to a given address\n\
  2431. setblocking() -- set or clear the blocking I/O flag\n\
  2432. setsockopt() -- set socket options\n\
  2433. shutdown() -- shut down traffic in one or both directions\n\
  2434. \n\
  2435. (*) not available on all platforms!)";
  2436.  
  2437. DL_EXPORT(void)
  2438. #if defined(MS_WINDOWS) || defined(PYOS_OS2) || defined(__BEOS__)
  2439. init_socket(void)
  2440. #else
  2441. initsocket(void)
  2442. #endif
  2443. {
  2444.     PyObject *m, *d;
  2445. #ifdef MS_WINDOWS
  2446.     if (!NTinit())
  2447.         return;
  2448.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2449. #else
  2450. #if defined(__TOS_OS2__)
  2451.     if (!OS2init())
  2452.         return;
  2453.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2454. #else
  2455. #if defined(__BEOS__)
  2456.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2457. #else
  2458.     m = Py_InitModule3("socket", PySocket_methods, module_doc);
  2459. #endif /* __BEOS__ */
  2460. #endif
  2461. #endif
  2462.     d = PyModule_GetDict(m);
  2463.     PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
  2464.     if (PySocket_Error == NULL)
  2465.         return;
  2466. #ifdef USE_SSL
  2467.     SSL_load_error_strings();
  2468.     SSLeay_add_ssl_algorithms();
  2469.     SSLErrorObject = PyErr_NewException("socket.sslerror", NULL, NULL);
  2470.     if (SSLErrorObject == NULL)
  2471.         return;
  2472.     PyDict_SetItemString(d, "sslerror", SSLErrorObject);
  2473.     Py_INCREF(&SSL_Type);
  2474.     if (PyDict_SetItemString(d, "SSLType",
  2475.                  (PyObject *)&SSL_Type) != 0)
  2476.         return;
  2477. #endif /* USE_SSL */
  2478.     PyDict_SetItemString(d, "error", PySocket_Error);
  2479.     PySocketSock_Type.ob_type = &PyType_Type;
  2480.     PySocketSock_Type.tp_doc = sockettype_doc;
  2481.     Py_INCREF(&PySocketSock_Type);
  2482.     if (PyDict_SetItemString(d, "SocketType",
  2483.                  (PyObject *)&PySocketSock_Type) != 0)
  2484.         return;
  2485.  
  2486.     /* Address families (we only support AF_INET and AF_UNIX) */
  2487. #ifdef AF_UNSPEC
  2488.     insint(d, "AF_UNSPEC", AF_UNSPEC);
  2489. #endif
  2490.     insint(d, "AF_INET", AF_INET);
  2491. #ifdef AF_UNIX
  2492.     insint(d, "AF_UNIX", AF_UNIX);
  2493. #endif /* AF_UNIX */
  2494. #ifdef AF_AX25
  2495.     insint(d, "AF_AX25", AF_AX25); /* Amateur Radio AX.25 */
  2496. #endif
  2497. #ifdef AF_IPX
  2498.     insint(d, "AF_IPX", AF_IPX); /* Novell IPX */
  2499. #endif
  2500. #ifdef AF_APPLETALK
  2501.     insint(d, "AF_APPLETALK", AF_APPLETALK); /* Appletalk DDP */
  2502. #endif
  2503. #ifdef AF_NETROM
  2504.     insint(d, "AF_NETROM", AF_NETROM); /* Amateur radio NetROM */
  2505. #endif
  2506. #ifdef AF_BRIDGE
  2507.     insint(d, "AF_BRIDGE", AF_BRIDGE); /* Multiprotocol bridge */
  2508. #endif
  2509. #ifdef AF_AAL5
  2510.     insint(d, "AF_AAL5", AF_AAL5); /* Reserved for Werner's ATM */
  2511. #endif
  2512. #ifdef AF_X25
  2513.     insint(d, "AF_X25", AF_X25); /* Reserved for X.25 project */
  2514. #endif
  2515. #ifdef AF_INET6
  2516.     insint(d, "AF_INET6", AF_INET6); /* IP version 6 */
  2517. #endif
  2518. #ifdef AF_ROSE
  2519.     insint(d, "AF_ROSE", AF_ROSE); /* Amateur Radio X.25 PLP */
  2520. #endif
  2521.  
  2522.     /* Socket types */
  2523.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  2524.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  2525. #ifndef __BEOS__
  2526. /* We have incomplete socket support. */
  2527.     insint(d, "SOCK_RAW", SOCK_RAW);
  2528.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  2529.     insint(d, "SOCK_RDM", SOCK_RDM);
  2530. #endif
  2531.  
  2532. #ifdef    SO_DEBUG
  2533.     insint(d, "SO_DEBUG", SO_DEBUG);
  2534. #endif
  2535. #ifdef    SO_ACCEPTCONN
  2536.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  2537. #endif
  2538. #ifdef    SO_REUSEADDR
  2539.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  2540. #endif
  2541. #ifdef    SO_KEEPALIVE
  2542.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  2543. #endif
  2544. #ifdef    SO_DONTROUTE
  2545.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  2546. #endif
  2547. #ifdef    SO_BROADCAST
  2548.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  2549. #endif
  2550. #ifdef    SO_USELOOPBACK
  2551.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  2552. #endif
  2553. #ifdef    SO_LINGER
  2554.     insint(d, "SO_LINGER", SO_LINGER);
  2555. #endif
  2556. #ifdef    SO_OOBINLINE
  2557.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  2558. #endif
  2559. #ifdef    SO_REUSEPORT
  2560.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  2561. #endif
  2562. #ifdef    SO_SNDBUF
  2563.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  2564. #endif
  2565. #ifdef    SO_RCVBUF
  2566.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  2567. #endif
  2568. #ifdef    SO_SNDLOWAT
  2569.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  2570. #endif
  2571. #ifdef    SO_RCVLOWAT
  2572.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  2573. #endif
  2574. #ifdef    SO_SNDTIMEO
  2575.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  2576. #endif
  2577. #ifdef    SO_RCVTIMEO
  2578.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  2579. #endif
  2580. #ifdef    SO_ERROR
  2581.     insint(d, "SO_ERROR", SO_ERROR);
  2582. #endif
  2583. #ifdef    SO_TYPE
  2584.     insint(d, "SO_TYPE", SO_TYPE);
  2585. #endif
  2586.  
  2587.     /* Maximum number of connections for "listen" */
  2588. #ifdef    SOMAXCONN
  2589.     insint(d, "SOMAXCONN", SOMAXCONN);
  2590. #else
  2591.     insint(d, "SOMAXCONN", 5);    /* Common value */
  2592. #endif
  2593.  
  2594.     /* Flags for send, recv */
  2595. #ifdef    MSG_OOB
  2596.     insint(d, "MSG_OOB", MSG_OOB);
  2597. #endif
  2598. #ifdef    MSG_PEEK
  2599.     insint(d, "MSG_PEEK", MSG_PEEK);
  2600. #endif
  2601. #ifdef    MSG_DONTROUTE
  2602.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  2603. #endif
  2604. #ifdef    MSG_DONTWAIT
  2605.     insint(d, "MSG_DONTWAIT", MSG_DONTWAIT);
  2606. #endif
  2607. #ifdef    MSG_EOR
  2608.     insint(d, "MSG_EOR", MSG_EOR);
  2609. #endif
  2610. #ifdef    MSG_TRUNC
  2611.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  2612. #endif
  2613. #ifdef    MSG_CTRUNC
  2614.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  2615. #endif
  2616. #ifdef    MSG_WAITALL
  2617.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  2618. #endif
  2619. #ifdef    MSG_BTAG
  2620.     insint(d, "MSG_BTAG", MSG_BTAG);
  2621. #endif
  2622. #ifdef    MSG_ETAG
  2623.     insint(d, "MSG_ETAG", MSG_ETAG);
  2624. #endif
  2625.  
  2626.     /* Protocol level and numbers, usable for [gs]etsockopt */
  2627. #ifdef    SOL_SOCKET
  2628.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  2629. #endif
  2630. #ifdef    SOL_IP
  2631.     insint(d, "SOL_IP", SOL_IP);
  2632. #else
  2633.     insint(d, "SOL_IP", 0);
  2634. #endif
  2635. #ifdef    SOL_IPX
  2636.     insint(d, "SOL_IPX", SOL_IPX);
  2637. #endif
  2638. #ifdef    SOL_AX25
  2639.     insint(d, "SOL_AX25", SOL_AX25);
  2640. #endif
  2641. #ifdef    SOL_ATALK
  2642.     insint(d, "SOL_ATALK", SOL_ATALK);
  2643. #endif
  2644. #ifdef    SOL_NETROM
  2645.     insint(d, "SOL_NETROM", SOL_NETROM);
  2646. #endif
  2647. #ifdef    SOL_ROSE
  2648.     insint(d, "SOL_ROSE", SOL_ROSE);
  2649. #endif
  2650. #ifdef    SOL_TCP
  2651.     insint(d, "SOL_TCP", SOL_TCP);
  2652. #else
  2653.     insint(d, "SOL_TCP", 6);
  2654. #endif
  2655. #ifdef    SOL_UDP
  2656.     insint(d, "SOL_UDP", SOL_UDP);
  2657. #else
  2658.     insint(d, "SOL_UDP", 17);
  2659. #endif
  2660. #ifdef    IPPROTO_IP
  2661.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  2662. #else
  2663.     insint(d, "IPPROTO_IP", 0);
  2664. #endif
  2665. #ifdef    IPPROTO_ICMP
  2666.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  2667. #else
  2668.     insint(d, "IPPROTO_ICMP", 1);
  2669. #endif
  2670. #ifdef    IPPROTO_IGMP
  2671.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  2672. #endif
  2673. #ifdef    IPPROTO_GGP
  2674.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  2675. #endif
  2676. #ifdef    IPPROTO_TCP
  2677.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  2678. #else
  2679.     insint(d, "IPPROTO_TCP", 6);
  2680. #endif
  2681. #ifdef    IPPROTO_EGP
  2682.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  2683. #endif
  2684. #ifdef    IPPROTO_PUP
  2685.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  2686. #endif
  2687. #ifdef    IPPROTO_UDP
  2688.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  2689. #else
  2690.     insint(d, "IPPROTO_UDP", 17);
  2691. #endif
  2692. #ifdef    IPPROTO_IDP
  2693.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  2694. #endif
  2695. #ifdef    IPPROTO_HELLO
  2696.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  2697. #endif
  2698. #ifdef    IPPROTO_ND
  2699.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  2700. #endif
  2701. #ifdef    IPPROTO_TP
  2702.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  2703. #endif
  2704. #ifdef    IPPROTO_XTP
  2705.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  2706. #endif
  2707. #ifdef    IPPROTO_EON
  2708.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  2709. #endif
  2710. #ifdef    IPPROTO_BIP
  2711.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  2712. #endif
  2713. /**/
  2714. #ifdef    IPPROTO_RAW
  2715.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  2716. #else
  2717.     insint(d, "IPPROTO_RAW", 255);
  2718. #endif
  2719. #ifdef    IPPROTO_MAX
  2720.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  2721. #endif
  2722.  
  2723.     /* Some port configuration */
  2724. #ifdef    IPPORT_RESERVED
  2725.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  2726. #else
  2727.     insint(d, "IPPORT_RESERVED", 1024);
  2728. #endif
  2729. #ifdef    IPPORT_USERRESERVED
  2730.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  2731. #else
  2732.     insint(d, "IPPORT_USERRESERVED", 5000);
  2733. #endif
  2734.  
  2735.     /* Some reserved IP v.4 addresses */
  2736. #ifdef    INADDR_ANY
  2737.     insint(d, "INADDR_ANY", INADDR_ANY);
  2738. #else
  2739.     insint(d, "INADDR_ANY", 0x00000000);
  2740. #endif
  2741. #ifdef    INADDR_BROADCAST
  2742.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  2743. #else
  2744.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  2745. #endif
  2746. #ifdef    INADDR_LOOPBACK
  2747.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  2748. #else
  2749.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  2750. #endif
  2751. #ifdef    INADDR_UNSPEC_GROUP
  2752.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  2753. #else
  2754.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  2755. #endif
  2756. #ifdef    INADDR_ALLHOSTS_GROUP
  2757.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  2758. #else
  2759.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  2760. #endif
  2761. #ifdef    INADDR_MAX_LOCAL_GROUP
  2762.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  2763. #else
  2764.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  2765. #endif
  2766. #ifdef    INADDR_NONE
  2767.     insint(d, "INADDR_NONE", INADDR_NONE);
  2768. #else
  2769.     insint(d, "INADDR_NONE", 0xffffffff);
  2770. #endif
  2771.  
  2772.     /* IP [gs]etsockopt options */
  2773. #ifdef    IP_OPTIONS
  2774.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  2775. #endif
  2776. #ifdef    IP_HDRINCL
  2777.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  2778. #endif
  2779. #ifdef    IP_TOS
  2780.     insint(d, "IP_TOS", IP_TOS);
  2781. #endif
  2782. #ifdef    IP_TTL
  2783.     insint(d, "IP_TTL", IP_TTL);
  2784. #endif
  2785. #ifdef    IP_RECVOPTS
  2786.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  2787. #endif
  2788. #ifdef    IP_RECVRETOPTS
  2789.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  2790. #endif
  2791. #ifdef    IP_RECVDSTADDR
  2792.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  2793. #endif
  2794. #ifdef    IP_RETOPTS
  2795.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  2796. #endif
  2797. #ifdef    IP_MULTICAST_IF
  2798.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  2799. #endif
  2800. #ifdef    IP_MULTICAST_TTL
  2801.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  2802. #endif
  2803. #ifdef    IP_MULTICAST_LOOP
  2804.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  2805. #endif
  2806. #ifdef    IP_ADD_MEMBERSHIP
  2807.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  2808. #endif
  2809. #ifdef    IP_DROP_MEMBERSHIP
  2810.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  2811. #endif
  2812. #ifdef    IP_DEFAULT_MULTICAST_TTL
  2813.     insint(d, "IP_DEFAULT_MULTICAST_TTL", IP_DEFAULT_MULTICAST_TTL);
  2814. #endif
  2815. #ifdef    IP_DEFAULT_MULTICAST_LOOP
  2816.     insint(d, "IP_DEFAULT_MULTICAST_LOOP", IP_DEFAULT_MULTICAST_LOOP);
  2817. #endif
  2818. #ifdef    IP_MAX_MEMBERSHIPS
  2819.     insint(d, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
  2820. #endif
  2821.  
  2822.     /* TCP options */
  2823. #ifdef    TCP_NODELAY
  2824.     insint(d, "TCP_NODELAY", TCP_NODELAY);
  2825. #endif
  2826. #ifdef    TCP_MAXSEG
  2827.     insint(d, "TCP_MAXSEG", TCP_MAXSEG);
  2828. #endif
  2829.  
  2830.     /* IPX options */
  2831. #ifdef    IPX_TYPE
  2832.     insint(d, "IPX_TYPE", IPX_TYPE);
  2833. #endif
  2834.  
  2835.     /* Initialize gethostbyname lock */
  2836. #ifdef USE_GETHOSTBYNAME_LOCK
  2837.     gethostbyname_lock = PyThread_allocate_lock();
  2838. #endif
  2839. }
  2840.